﻿using DTcms.Common;
using DTcms.Model;
using DTcms.Web.Mvc.UI;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using DTcms.Cache.Factory;
using System.Xml;
using DTcms.API.Weixin.Common;
using Senparc.Weixin.MP.Entities.Menu;
using Newtonsoft.Json;
using DTcms.SMS;

namespace DTcms.Web.Mvc.Areas.Admin.Controllers
{
    /// <summary>
    /// 这里是网页端和移动程序端的使用的API的共同核心
    /// 网页端虽然使用WebApi
    /// 移动端虽然使用App
    /// 但其核心是完全一致的，差异的只是各自参数情况
    /// 本类将包装所有的Api的逻辑和数据，显示完整的参数列表，供两处，按自己的参数情况使用
    /// </summary>
    public class BaseApi : UnitController
    {
        #region 全局变量声明
        /// <summary>
        /// 异常日志
        /// </summary>
        LogHelper log = new LogHelper();

        string defaultpassword = "0|0|0|0"; //默认显示密码
        CRMComm cpp = new CRMComm(); //获取AccessToKen类
        private SaveModel save = new SaveModel();
        #endregion

        #region 用户登录
        //用户登录
        public JsonResult LoginJson(string username, string password, string code)
        {
            //检查用户名密码
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return Json(new { status = 0, msg = "请输入用户名或密码！" });
            }

            if (System.Web.HttpContext.Current.Session["AdminLoginSun"] == null)
            {
                System.Web.HttpContext.Current.Session["AdminLoginSun"] = 1;
            }
            else
            {
                System.Web.HttpContext.Current.Session["AdminLoginSun"] = Convert.ToInt32(System.Web.HttpContext.Current.Session["AdminLoginSun"]) + 1;
            }
            //判断登录错误次数
            if (System.Web.HttpContext.Current.Session["AdminLoginSun"] != null && Convert.ToInt32(System.Web.HttpContext.Current.Session["AdminLoginSun"]) > 5)
            {
                return Json(new { status = 0, msg = "错误超过5次，关闭浏览器重新登录！" });
            }
            BLL.manager bll = new BLL.manager();
            Model.manager model = bll.GetModel(username, password, true);
            if (model == null)
            {
                return Json(new { status = 0, msg = "用户名或密码错误，请重试！" });
            }
            System.Web.HttpContext.Current.Session[DTKeys.SESSION_ADMIN_INFO] = model;
            System.Web.HttpContext.Current.Session.Timeout = 45;
            //写入登录日志
            Model.siteconfig siteConfig = new BLL.siteconfig().loadConfig();
            if (siteConfig.logstatus > 0)
            {
                new BLL.manager_log().Add(model.id, model.user_name, DTEnums.ActionEnum.Login.ToString(), "用户登录");
            }
            //写入Cookies
            //开启防Session超时
            Utils.WriteCookie("LGRememberName", model.user_name, 14400);
            Utils.WriteCookie("AdminName", "DTcms", DESEncrypt.Encrypt(model.user_name, DTKeys.COOKIE_KEY));
            Utils.WriteCookie("AdminPwd", "DTcms", DESEncrypt.Encrypt(model.password, DTRequest.GetIP()));
            return Json(new { status = 1, msg = "正在登陆中。。。" });
        }
        #endregion

        #region 文章内容管理
        //设置文章状态√
        public JsonResult ArticleStatus(int channel_id, int id, string cmdName)
        {
            BLL.article bll = new BLL.article();
            Model.article model = bll.GetModel(channel_id, id);
            if (model != null)
            {
                switch (cmdName)
                {
                    case "lbtnIsMsg":
                        if (model.is_msg == 1)
                            bll.UpdateField(channel_id, id, "is_msg=0");
                        else
                            bll.UpdateField(channel_id, id, "is_msg=1");
                        break;
                    case "lbtnIsTop":
                        if (model.is_top == 1)
                            bll.UpdateField(channel_id, id, "is_top=0");
                        else
                            bll.UpdateField(channel_id, id, "is_top=1");
                        break;
                    case "lbtnIsRed":
                        if (model.is_red == 1)
                            bll.UpdateField(channel_id, id, "is_red=0");
                        else
                            bll.UpdateField(channel_id, id, "is_red=1");
                        break;
                    case "lbtnIsHot":
                        if (model.is_hot == 1)
                            bll.UpdateField(channel_id, id, "is_hot=0");
                        else
                            bll.UpdateField(channel_id, id, "is_hot=1");
                        break;
                    case "lbtnIsSlide":
                        if (model.is_slide == 1)
                            bll.UpdateField(channel_id, id, "is_slide=0");
                        else
                            bll.UpdateField(channel_id, id, "is_slide=1");
                        break;
                }
            }
            return Json(new { status = 1, msg = "状态修改成功！" });
        }

        //批量移动√
        public JsonResult ArticleMove(int channel_id, List<int> ids, int category_id)
        {
            if (category_id == 0)
            {
                return Json(new { status = 0, msg = "移动类别未选择！" });
            }
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_list", DTEnums.ActionEnum.Audit.ToString()); //检查权限
            BLL.article bll = new BLL.article();
            int sucCount = 0; //成功数量
            foreach (int id in ids)
            {
                if (bll.UpdateField(channel_id, id, "category_id=" + category_id))
                {
                    sucCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "批量移动" + channel_name + "频道内容分类"); //记录日志
            return Json(new { status = 1, msg = "批量移动成功" + sucCount + "条！" });
        }

        //批量审核√
        public JsonResult ArticleAudit(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_list", DTEnums.ActionEnum.Audit.ToString()); //检查权限
            BLL.article bll = new BLL.article();
            foreach (int id in ids)
            {
                bll.UpdateField(channel_id, id, "status=0");
            }
            AddAdminLog(DTEnums.ActionEnum.Audit.ToString(), "审核" + channel_name + "频道内容信息"); //记录日志
            return Json(new { status = 1, msg = "批量审核成功！" });
        }

        //加入回收站√
        public JsonResult ArticleRecycle(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_list", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            BLL.article bll = new BLL.article();
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            foreach (int id in ids)
            {
                if (bll.UpdateField(channel_id, id, "status=2"))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Audit.ToString(), "移入回收站" + channel_name + "频道内容信息"); //记录日志
            return Json(new { status = 1, msg = "批量移入回收站成功！" });
        }

        //批量删除√
        public JsonResult ArticleDelete(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            if (string.IsNullOrEmpty(channel_name))
            {
                return Json(new { status = 1, msg = "频道不存在！" });
            }
            ChkAdminLevel("channel_" + channel_name + "_list", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.article bll = new BLL.article();
            foreach (int id in ids)
            {
                if (bll.Delete(channel_id, id))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除" + channel_name + "频道内容成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        //微信推送√
        public JsonResult ArticleWxPost(int channel_id, List<int> ids, int accountId)
        {
            Model.site_channel channel_model = new BLL.site_channel().GetModel(channel_id);
            if (channel_model == null)
            {
                return Json(new { status = 0, msg = "频道不存在！" });
            }
            ChkAdminLevel("channel_" + channel_model.name + "_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
            //检查该微信公众号是否开启消息推送功能
            Model.weixin_account wxModel = new BLL.weixin_account().GetModel(1);
            if (wxModel == null || wxModel.is_push == 0)
            {
                return Json(new { status = 0, msg = "微信账户未开启消息推送！" });
            }
            string errmsg = string.Empty; //错误消息
            string linkdomain = GetLinkDomain(channel_id); //链接网址
            List<Model.article> artls = new List<Model.article>(); //选中文章的实体
            List<Senparc.Weixin.MP.AdvancedAPIs.GroupMessage.NewsModel> ls = new List<Senparc.Weixin.MP.AdvancedAPIs.GroupMessage.NewsModel>();

            BLL.article bll = new BLL.article();
            foreach (int id in ids)
            {
                Model.article model = bll.GetWXModel(channel_id, id); //获取文章实体
                if (model == null || string.IsNullOrEmpty(model.img_url.ToString()))
                {
                    return Json(new { status = 0, msg = "错误：所选择信息有些没有图片！" });
                }
                artls.Add(model);
            }
            if (accountId == 0)
            {
                return Json(new { status = 0, msg = "错误：AccountId未获取！" });
            }
            //判断是否超出推送的数量
            if (artls.Count == 0 || artls.Count > 10)
            {
                return Json(new { status = 0, msg = "错误：推送消息数量应在1-10条范围！" });
            }
            //上传及群发消息
            foreach (Model.article modelt in artls)
            {
                //上传永久素材获取media_id
                string mediaId = cpp.UploadForeverMedia(accountId, Utils.GetMapPath(modelt.img_url), out errmsg);
                if (string.IsNullOrEmpty(mediaId))
                {
                    return Json(new { status = 0, msg = "错误：" + errmsg });
                }
                //添加消息实体
                Senparc.Weixin.MP.AdvancedAPIs.GroupMessage.NewsModel newsModel = new Senparc.Weixin.MP.AdvancedAPIs.GroupMessage.NewsModel();
                newsModel.thumb_media_id = mediaId; //图文消息缩略图的media_id
                newsModel.title = modelt.title; //图文消息的标题
                newsModel.content_source_url = linkdomain; //点击“阅读原文”后的页面
                newsModel.content = ReplaceImagesPath(modelt.content); //图文消息页面的内容，替换图片路径
                newsModel.digest = modelt.zhaiyao; //图文消息的描述
                newsModel.show_cover_pic = "1"; //是否显示封面，1为显示，0为不显示
                ls.Add(newsModel); //添加实体到泛型
            }
            //开始群发消息
            bool result = cpp.SendGroupMessageByGroupId(accountId, ls, out errmsg);
            if (!result)
            {
                return Json(new { status = 0, msg = "错误：" + errmsg });
            }
            return Json(new { status = 1, msg = "微信消息推送成功：" });
        }

        //文章内容绑定
        public DataTable ArticleBind(int _channel_id, int _category_id, string _strWhere, string _orderby, out int totalCount, int page = 1, int pageSize = 10)
        {
            Model.site_channel channel_model = new BLL.site_channel().GetModel(_channel_id);
            if (channel_model == null)
            {
                totalCount = 0;
                return new DataTable();
            }

            //图表或列表显示
            BLL.article bll = new BLL.article();
            DataTable dt = bll.GetList(_channel_id, _category_id, pageSize, page, _strWhere, _orderby, out totalCount).Tables[0];
            if (dt.Rows.Count > 0)
            {
                string link_url = null;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    link_url = dt.Rows[i]["link_url"].ToString();
                    if (string.IsNullOrEmpty(link_url))
                    {
                        dt.Rows[i]["link_url"] = get_url_rewrite(channel_model.name, "detail", dt.Rows[i]["call_index"].ToString(), Utils.StrToInt(dt.Rows[i]["id"].ToString(), 0));
                    }
                }
            }
            return dt;
        }

        #region 赋值操作
        public Model.article ArticleInfo(int _id, int channel_id)
        {
            BLL.article bll = new BLL.article();
            Model.article ArticleModel = bll.GetModel(channel_id, _id);
            return ArticleModel;
        }
        #endregion

        #region 增加、编辑操作
        public SaveModel ArticleSave(string _action, int _id, int _channel_id, Model.article t)
        {
            BLL.article bll = new BLL.article();
            Model.article model = new article();
            string modelImg = string.Empty;//原IMG图片
            if (_id > 0 && _action == DTEnums.ActionEnum.Edit.ToString())//编辑
            {
                model = bll.GetModel(_channel_id, _id);
                modelImg = model.img_url;
                model = t;
                model.update_time = DateTime.Now;
            }
            else
            {
                model = t;
                model.is_sys = 1; //管理员发布
                model.user_name = GetAdminInfo().user_name; //获得当前登录用户名
                model.add_time = Utils.StrToDateTime(model.add_time.ToString());
            }
            Model.sites site = new BLL.sites().GetSiteModel(_channel_id);
            Model.site_channel channelModel = new BLL.site_channel().GetModel(_channel_id);

            model.site_id = site.id;
            model.channel_id = _channel_id;
            //内容摘要提取内容前255个字符
            if (string.IsNullOrEmpty(model.zhaiyao))
            {
                model.zhaiyao = Utils.DropHTML(model.content, 255);
            }
            else
            {
                model.zhaiyao = Utils.DropHTML(model.zhaiyao, 255);
            }
            //封面图片
            if (string.IsNullOrEmpty(model.img_url) && !string.IsNullOrEmpty(DTRequest.GetFormString("autoImg")))
            {
                model.img_url = AutoGetFirstImage(model.content, channelModel);
            }
            model.sort_id = Utils.StrToInt(model.sort_id.ToString(), 99);
            model.is_msg = DTRequest.GetFormString("is_msg").Contains("true") ? 1 : 0;
            model.is_top = DTRequest.GetFormString("is_top").Contains("true") ? 1 : 0;
            model.is_red = DTRequest.GetFormString("is_red").Contains("true") ? 1 : 0;
            model.is_hot = DTRequest.GetFormString("is_hot").Contains("true") ? 1 : 0;
            model.is_slide = DTRequest.GetFormString("is_slide").Contains("true") ? 1 : 0;

            model.fields = SetFieldValues(_channel_id); //扩展字段赋值
            //视频截图封面
            string is_videoImg = DTRequest.GetFormString("videoImg");
            if (model.fields.ContainsKey("video_src") && !string.IsNullOrEmpty(is_videoImg))
            {
                string img_url = model.fields["video_src"].Substring(0, model.fields["video_src"].Length - 4) + ".jpg";//截图存储地址
                VideoHelper ffmpeg = new VideoHelper();
                //缩略图尺寸
                Model.site_channel_thum thum = channelModel.channel_thums.Find(p => p.class_id == 1 && p.is_lock == 1);
                string imgSize = string.Empty;
                if (thum != null)
                {
                    imgSize = thum.width + "*" + thum.height;
                }
                else
                {
                    imgSize = "200*200";
                }
                string imgPhysicalPath = ffmpeg.CatchImg(model.fields["video_src"], img_url, imgSize, "5");//5秒中截图
                if (!string.IsNullOrEmpty(imgPhysicalPath))
                {
                    model.img_url = imgPhysicalPath;
                }
            }
            #region 保存相册
            //检查是否有自定义图片
            if (string.IsNullOrEmpty(t.img_url))
            {
                t.img_url = DTRequest.GetFormString("hidFocusPhoto");
            }
            if (t.albums != null)
            {
                t.albums.Clear();
            }
            string[] albumArr = DTRequest.GetFormValues("hid_photo_name");
            string[] remarkArr = DTRequest.GetFormValues("hid_photo_remark");
            string[] sortArr = DTRequest.GetFormValues("hid_photo_sort");
            if (albumArr != null)
            {
                List<Model.article_albums> ls = new List<Model.article_albums>();
                for (int i = 0; i < albumArr.Length; i++)
                {
                    string[] imgArr = albumArr[i].Split('|');
                    int img_id = Utils.StrToInt(imgArr[0], 0);
                    int sort_id = Utils.StrToInt(sortArr[i], 99);
                    if (imgArr.Length == 3)
                    {
                        if (!string.IsNullOrEmpty(remarkArr[i]))
                        {
                            ls.Add(new Model.article_albums { id = img_id, article_id = _id, original_path = imgArr[1], thumb_path = imgArr[2], remark = remarkArr[i], sort_id = sort_id, channel_id = _channel_id });
                        }
                        else
                        {
                            ls.Add(new Model.article_albums { id = img_id, article_id = _id, original_path = imgArr[1], thumb_path = imgArr[2], sort_id = sort_id, channel_id = _channel_id });
                        }
                    }
                }
                t.albums = ls;
            }
            #endregion
            #region 保存附件
            if (t.attach != null)
            {
                t.attach.Clear();
            }
            string[] attachIdArr = DTRequest.GetFormValues("hid_attach_id");
            string[] attachFileNameArr = DTRequest.GetFormValues("hid_attach_filename");
            string[] attachFilePathArr = DTRequest.GetFormValues("hid_attach_filepath");
            string[] attachFileSizeArr = DTRequest.GetFormValues("hid_attach_filesize");
            string[] attachPointArr = DTRequest.GetFormValues("txt_attach_point");
            if (attachIdArr != null && attachFileNameArr != null && attachFilePathArr != null && attachFileSizeArr != null && attachPointArr != null
                && attachIdArr.Length > 0 && attachFileNameArr.Length > 0 && attachFilePathArr.Length > 0 && attachFileSizeArr.Length > 0 && attachPointArr.Length > 0)
            {
                List<Model.article_attach> ls = new List<Model.article_attach>();
                for (int i = 0; i < attachFileNameArr.Length; i++)
                {
                    int attachId = Utils.StrToInt(attachIdArr[i], 0);
                    int fileSize = Utils.StrToInt(attachFileSizeArr[i], 0);
                    string fileExt = Utils.GetFileExt(attachFilePathArr[i]);
                    int _point = Utils.StrToInt(attachPointArr[i], 0);
                    ls.Add(new Model.article_attach { id = attachId, article_id = _id, file_name = attachFileNameArr[i], file_path = attachFilePathArr[i], file_size = fileSize, file_ext = fileExt, point = _point, channel_id = _channel_id });
                }
                t.attach = ls;
            }
            #endregion
            #region 保存自定义参数
            if (t.attribute != null)
            {
                t.attribute.Clear();
            }
            //保存自定义参数
            string[] attributeNameArr = DTRequest.GetFormValues("hid_attribute_name");
            string[] attributeValueArr = DTRequest.GetFormValues("hid_attribute_value");

            if (attributeNameArr != null && attributeValueArr != null && attributeNameArr.Length > 0 && attributeValueArr.Length > 0)
            {
                List<Model.article_attribute> ls = new List<Model.article_attribute>();
                for (int i = 0; i < attributeNameArr.Length; i++)
                {
                    ls.Add(new Model.article_attribute { title = attributeNameArr[i], value = attributeValueArr[i] });
                }
                t.attribute = ls;
            }
            #endregion
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                if (bll.Update(model))
                {
                    if (!string.IsNullOrEmpty(modelImg))//修改成功后 删除原来的文章图片
                    {
                        if (model.img_url != modelImg)
                        {
                            FileHelper.DeleteFile(modelImg);
                        }
                    }
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改" + channelModel.name + "频道内容:" + t.title); //记录日志
                    #region 是否开启百度推送
                    if (t.status == 0 && site.bdsend == 1 && !string.IsNullOrEmpty(site.bdtoken))
                    {
                        string url = get_url_rewrite(channelModel.name, "detail", t.call_index, model.id);
                        if (!string.IsNullOrEmpty(url))
                        {
                            if (string.IsNullOrEmpty(site.domain))
                            {
                                url = siteConfig.weburl + url;
                            }
                            else
                            {
                                url = site.domain + url;
                            }
                            //原创推送
                            if (!SeoHelper.BaiduUpdate(url, site.bdtoken))
                            {
                                //百度Ping
                                SeoHelper.PingBaidu(url);
                            }
                        }
                    }
                    #endregion
                    return new SaveModel
                    {
                        msg = "修改信息成功！",
                        status = 1
                    };
                }
                return new SaveModel
                {
                    msg = "保存过程中发生错误啦！",
                    status = 0
                };
            }
            else
            {
                model.id = bll.Add(model);
                if (model.id > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加" + channelModel.name + "频道内容:" + model.title); //记录日志
                    #region 是否开启百度推送
                    if (model.status == 0 && site.bdsend == 1 && !string.IsNullOrEmpty(site.bdtoken))
                    {
                        string url = get_url_rewrite(channelModel.name, "detail", model.call_index, model.id);
                        if (!string.IsNullOrEmpty(url))
                        {
                            if (string.IsNullOrEmpty(site.domain))
                            {
                                url = siteConfig.weburl + url;
                            }
                            else
                            {
                                url = site.domain + url;
                            }
                            //原创推送
                            if (!SeoHelper.BaiduUrls(url, site.bdtoken, true))
                            {
                                //百度Ping
                                SeoHelper.PingBaidu(url);
                            }
                        }
                    }
                    #endregion
                    return new SaveModel
                    {
                        msg = "添加信息成功！",
                        status = 1
                    };
                }
                return new SaveModel
                {
                    msg = "保存过程中发生错误啦！",
                    status = 0
                };
            }
        }
        #endregion

        #region 创建其它扩展字段
        public List<Model.article_attribute_field> CreateOtherField(int _channel_id)
        {
            List<Model.article_attribute_field> otherFieldList = new BLL.article_attribute_field().GetModelList(_channel_id, "is_sys=0");
            return otherFieldList;
        }
        #endregion

        #region 扩展字段赋值
        private Dictionary<string, string> SetFieldValues(int _channel_id)
        {
            List<Model.article_attribute_field> list = new BLL.article_attribute_field().GetModelList(_channel_id, "");
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string paramName = string.Empty;
            foreach (var dr in list)
            {
                //查找相应的控件
                switch (dr.control_type)
                {
                    case "single-text": //单行文本
                        paramName = "field_control_" + dr.name;
                        string single_text = DTRequest.GetFormString(paramName);
                        if (!string.IsNullOrEmpty(single_text))
                        {
                            dic.Add(dr.name, DTRequest.GetFormString(paramName));
                        }
                        break;
                    case "multi-text": //多行文本
                        goto case "single-text";
                    case "editor": //编辑器
                        paramName = "field_control_" + dr.name;
                        string editor = DTRequest.GetFormString(paramName);
                        if (!string.IsNullOrEmpty(editor))
                        {
                            dic.Add(dr.name, editor);
                        }
                        break;
                    case "images": //图片上传
                        goto case "single-text";
                    case "video": //视频上传
                        goto case "single-text";
                    case "number": //数字
                        goto case "single-text";
                    case "checkbox": //复选框
                        paramName = "field_control_" + dr.name;
                        string checkbox = DTRequest.GetFormString(paramName);
                        if (!string.IsNullOrEmpty(checkbox))
                        {
                            if (checkbox.Contains("true"))
                            {
                                dic.Add(dr.name, "1");
                            }
                            else
                            {
                                dic.Add(dr.name, "0");
                            }
                        }
                        break;
                    case "multi-radio": //多项单选
                        string[] items_option = dr.item_option.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                        for (int i = 0; i < items_option.Length; i++)
                        {
                            string[] valItemArr = items_option[i].Split('|');
                            if (valItemArr.Length == 2)
                            {
                                paramName = "field_control_" + dr.name;
                                string multi_radio = DTRequest.GetFormString(paramName);
                                if (!string.IsNullOrEmpty(multi_radio))
                                {
                                    dic.Add(dr.name, multi_radio);
                                    break;
                                }
                            }
                        }
                        break;
                    case "multi-checkbox": //多项多选
                        paramName = "field_control_" + dr.name;
                        string multi_checkbox = DTRequest.GetFormString(paramName);
                        StringBuilder tempStr = new StringBuilder();
                        if (!string.IsNullOrEmpty(multi_checkbox))
                        {
                            tempStr.AppendFormat(",{0},", multi_checkbox);
                        }
                        dic.Add(dr.name, Utils.DelLastComma(tempStr.ToString()));
                        break;
                    case "similar": //同类选择
                        string[] idArr = DTRequest.GetFormValues("field_control_" + dr.name);
                        if (idArr != null && idArr.Length > 0)
                        {
                            List<string> idList = new List<string>();
                            for (int i = 0; i < idArr.Length; i++)
                            {
                                if (!idList.Contains(idArr[i]))
                                {
                                    idList.Add(idArr[i]);
                                }
                            }
                            dic.Add(dr.name, string.Join(",", idList));
                        }
                        else
                        {
                            dic.Add(dr.name, dr.default_value);
                        }
                        break;
                }
            }
            return dic;
        }
        #endregion

        #region 显示默认扩展字段
        public List<Model.article_attribute_field> ShowSysField(int _channel_id)
        {
            //查找该频道所选的默认字段
            List<Model.article_attribute_field> ls = new BLL.article_attribute_field().GetModelList(_channel_id, "is_sys=1");
            return ls;
        }
        #endregion

        #region 扩展字段赋值
        public List<Model.article_attribute_field> AttributeFieldList(int ChannelId)
        {
            List<Model.article_attribute_field> ls1 = new BLL.article_attribute_field().GetModelList(ChannelId, "");
            return ls1;
        }
        #endregion

        #region 内容回收站
        #region 数据绑定
        public List<Model.article> RecycleBind(int _channel_id, int _category_id, string _strWhere, string _orderby, int page = 1, int pageSize = 10, int totalCount = 0)
        {
            //图表或列表显示
            BLL.article bll = new BLL.article();
            List<Model.article> model = bll.GetListPage(_channel_id, _category_id, pageSize, page, _strWhere, _orderby, out totalCount);
            return model;
        }
        #endregion

        //删除
        public JsonResult RecycleDelete(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_recycle", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            BLL.article bll = new BLL.article();
            //获取站点信息
            Model.sites site = new BLL.sites().GetSiteModel(channel_id);
            foreach (int id in ids)
            {
                Model.article model = bll.GetModel(channel_id, id);
                if (null != model)
                {
                    if (bll.Delete(channel_id, id))
                    {
                        sucCount++;
                        //是否开启百度推送
                        if (site.bdsend == 1 && !string.IsNullOrEmpty(site.bdtoken))
                        {
                            string url = get_url_rewrite(channel_name, "detail", model.call_index, model.id);
                            if (!string.IsNullOrEmpty(url))
                            {
                                if (string.IsNullOrEmpty(site.domain))
                                {
                                    url = siteConfig.weburl + url;
                                }
                                else
                                {
                                    url = site.domain + url;
                                }
                                SeoHelper.BaiduDel(url, site.bdtoken);
                            }
                        }
                    }
                    else
                    {
                        errorCount++;
                    }
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除Tags标签成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        //审核
        public JsonResult RecycleAudit(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_recycle", DTEnums.ActionEnum.Audit.ToString()); //检查权限
            BLL.article bll = new BLL.article();
            foreach (int id in ids)
            {
                bll.UpdateField(channel_id, id, "status=0");
            }
            AddAdminLog(DTEnums.ActionEnum.Audit.ToString(), "审核" + channel_name + "频道内容信息"); //记录日志
            return Json(new { status = 1, msg = "批量审核成功！" });
        }
        #endregion

        #endregion

        #region 文章类别
        #region 绑定类别
        public List<SelectListItem> CategoryTreeBind(int _channel_id, out IList<int> catlist)
        {
            List<SelectListItem> categoryListItems = new List<SelectListItem>();
            Model.site_channel channel_model = new BLL.site_channel().GetModel(_channel_id);
            catlist = new List<int>();
            if (channel_model == null)
            {
                return categoryListItems;
            }

            //获取类别列表
            int id;
            int ClassLayer;
            string nav_name, Title;
            Model.manager_role model = GetAdminRole();  //获取管理员角色
            DataTable dt = new BLL.article_category().GetList(0, _channel_id, "");
            foreach (DataRow dr in dt.Rows)
            {
                id = Convert.ToInt32(dr["id"]);
                nav_name = string.Format("channel_{0}_category_{1}", channel_model.name, id);
                if (model.role_type > 1)
                {
                    if (null == model.manager_role_values.Find(p => p.nav_name == nav_name && p.action_type == DTEnums.ActionEnum.Show.ToString()))
                    {
                        continue;
                    }
                }
                catlist.Add(id);

                ClassLayer = int.Parse(dr["class_layer"].ToString());
                Title = dr["title"].ToString();

                if (ClassLayer == 1)
                {
                    categoryListItems.Add(new SelectListItem() { Text = Title, Value = id.ToString() });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    categoryListItems.Add(new SelectListItem() { Text = Title, Value = id.ToString() });
                }
            }
            return categoryListItems;
        }
        #endregion

        #region 所有类别
        public DataTable CategoryBind(int channel_id)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            string strWhere = string.Empty;
            DataTable dt;
            //获取管理员
            Model.manager_role modelt = GetAdminRole();  //获取管理员角色
            BLL.article_category bll = new BLL.article_category();
            if (modelt.role_type > 1)
            {
                int cid = 0;
                string nav_name;
                IList<int> idlist = new List<int>();
                dt = bll.GetList(0, channel_id, "");
                foreach (DataRow dr in dt.Rows)
                {
                    cid = Convert.ToInt32(dr["id"]);
                    nav_name = string.Format("channel_{0}_category_{1}", channel_name, cid);
                    if (null == modelt.manager_role_values.Find(p => p.nav_name == nav_name && p.action_type == DTEnums.ActionEnum.Show.ToString()))
                    {
                        continue;
                    }
                    idlist.Add(cid);
                }
                if (idlist.Count > 0)
                {
                    strWhere += "id in (" + string.Join(",", idlist) + ")";
                }
            }
            dt = bll.GetList(0, channel_id, strWhere);
            //遍历
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dt.Rows[i]["link_url"].ToString()))
                {
                    string link_url = get_url_rewrite(channel_name, "list", dt.Rows[i]["call_index"].ToString(), Utils.StrToInt(dt.Rows[i]["id"].ToString(), 0));
                    if (string.IsNullOrEmpty(link_url))
                    {
                        dt.Rows[i]["link_url"] = "javascript:;";
                    }
                    else
                    {
                        dt.Rows[i]["link_url"] = link_url;
                    }
                }
            }
            return dt;
        }
        public List<SelectListItem> CategoryBind(int channel_id, out string return_term)
        {
            BLL.article_category bll = new BLL.article_category();
            return_term = string.Empty;
            string strWhere = string.Empty;
            //获取管理员
            Model.manager adminModel = GetAdminInfo();
            if (adminModel.role_type != 1)
            {
                List<int> idlist = new List<int>();
                //获取频道名称
                string channel_name = new BLL.site_channel().GetChannelName(channel_id);
                //获取权限列表
                string nav_name = "channel_" + channel_name + "_category_";
                DataTable dt2 = new BLL.manager_role_value().FillDataSet(0, string.Format("role_id={0} and action_type='Show' and nav_name like '{1}%'", adminModel.role_id, nav_name), "").Tables[0];
                if (dt2.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt2.Rows)
                    {
                        idlist.Add(int.Parse(dr["nav_name"].ToString().Replace(nav_name, string.Empty)));
                    }
                }
                else
                {
                    idlist.Add(0);
                }
                return_term = string.Join(",", idlist);
                strWhere = string.Format("id in ({0})", return_term);
            }
            DataTable dt = bll.GetList(0, channel_id, strWhere);

            List<SelectListItem> categoryListItems = new List<SelectListItem>();
            foreach (DataRow dr in dt.Rows)
            {
                string Id = dr["id"].ToString();
                int ClassLayer = int.Parse(dr["class_layer"].ToString());
                string Title = dr["title"].ToString();

                if (ClassLayer == 1)
                {
                    categoryListItems.Add(new SelectListItem() { Text = Title, Value = Id });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    categoryListItems.Add(new SelectListItem() { Text = Title, Value = Id });
                }
            }
            return categoryListItems;
        }
        #endregion

        //删除
        public JsonResult CategoryDelete(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_category", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            BLL.article_category bll = new BLL.article_category();
            int sucCount = 0;
            int errorCount = 0;
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除" + channel_name + "频道栏目分类数据"); //记录日志
            return Json(new { status = 1, msg = "删除数据成功！" });
        }

        #region 增加、编辑操作
        public SaveModel CategorySave(string _action, int _id, int _channel_id, Model.article_category t)
        {
            BLL.article_category bll = new BLL.article_category();
            Model.site_channel channelModel = new BLL.site_channel().GetModel(_channel_id);
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("channel_" + channelModel.name + "_category", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.article_category model = bll.Get(_id);

                if (bll.Update(t))
                {
                    //判断上传图片
                    if (!string.IsNullOrEmpty(t.img_url) && model.img_url != t.img_url)
                    {
                        //上传前先删除原图片
                        if (!string.IsNullOrEmpty(model.img_url))
                        {
                            Utils.DeleteFile(model.img_url);
                        }
                    }
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改" + channelModel.name + "频道栏目分类:" + model.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改类别成功！",
                    status = 1
                };
            }
            else
            {
                ChkAdminLevel("channel_" + channelModel.name + "_category", DTEnums.ActionEnum.Add.ToString()); //检查权限
                //获取管理员
                int rolo_id = 0;
                Model.manager adminModel = GetAdminInfo();
                if (adminModel.role_type != 1)
                {
                    rolo_id = adminModel.role_id;
                }
                if (bll.Add(t, rolo_id) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加" + channelModel.name + "频道栏目分类:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加类别成功！",
                    status = 1
                };
            }
        }
        #endregion

        #region 赋值操作
        public Model.article_category CategoryInfo(int _id)
        {
            BLL.article_category bll = new BLL.article_category();
            Model.article_category model = bll.GetModel(_id);
            return model;
        }
        #endregion
        #endregion

        #region 文章评论
        //评论删除
        public JsonResult CommentDelete(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_comment", DTEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            BLL.article_comment bll = new BLL.article_comment();
            //获取站点信息
            Model.sites site = new BLL.sites().GetSiteModel(channel_id);
            foreach (int id in ids)
            {
                if (bll.Delete("id=" + id + " and channel_id=" + channel_id) > 0)
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除" + channel_name + "频道评论成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        //评论审核
        public JsonResult CommentAudit(int channel_id, List<int> ids)
        {
            string channel_name = new BLL.site_channel().GetChannelName(channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_comment", DTEnums.ActionEnum.Audit.ToString()); //检查权限
            BLL.article_comment bll = new BLL.article_comment();
            if (ids.Count() == 0)
            {
                return Json(new { status = 0, msg = "请选择需要审核的记录！" });
            }
            foreach (int id in ids)
            {
                bll.UpdateFile("channel_id=" + channel_id + " and id=" + id, "is_lock=0");
            }
            AddAdminLog(DTEnums.ActionEnum.Audit.ToString(), "审核" + channel_name + "频道评论信息"); //记录日志
            return Json(new { status = 1, msg = "审核通过成功！" });
        }

        #region 数据绑定
        public Page<Model.article_comment> CommentBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.article_comment bll = new BLL.article_comment();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        #region 赋值操作
        public Model.article_comment CommentInfo(int _id)
        {
            Model.article_comment model = new BLL.article_comment().Get(_id); //取得评论实体
            model.reply_content = Utils.ToTxt(model.reply_content);
            return model;
        }
        #endregion

        #region 编辑操作
        public SaveModel CommentSave(int id, Model.article_comment t)
        {
            BLL.article_comment bll = new BLL.article_comment();
            Model.article_comment model = bll.GetModel(id);
            string channel_name = new BLL.site_channel().GetChannelName(model.channel_id); //取得频道名称
            ChkAdminLevel("channel_" + channel_name + "_comment", DTEnums.ActionEnum.Reply.ToString()); //检查权限
            model.is_reply = 1;
            model.reply_content = Utils.ToHtml(t.reply_content);
            model.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;
            model.reply_time = DateTime.Now;
            //if (!string.IsNullOrEmpty(model.reply_content) && model.is_email == 1 && !string.IsNullOrEmpty(model.email))//发送回复邮件
            //{
            //    //取得邮件模板内容
            //    Model.mail_template mailModel = new BLL.mail_template().GetModel(new { call_index = "adminreply" });
            //    Model.article Article = new BLL.article().GetModel(model.channel_id, model.article_id);
            //    if (mailModel != null)
            //    {
            //        //替换标签
            //        string mailTitle = mailModel.maill_title;//邮箱标题
            //        mailTitle = mailTitle.Replace("{email}", model.email);

            //        string mailContent = mailModel.content;//邮箱内容
            //        mailContent = mailContent.Replace("{email}", model.email);
            //        mailContent = mailContent.Replace("{webname}", siteConfig.webname);
            //        mailContent = mailContent.Replace("{title}", Article.title);
            //        mailContent = mailContent.Replace("{linkurl}", new BaseController().get_url_rewrite(Article.channel_id, Article.call_index, Article.id));
            //        mailContent = mailContent.Replace("{replycontent}", model.reply_content);
            //        mailContent = mailContent.Replace("{weburl}", siteConfig.weburl);
            //        mailContent = mailContent.Replace("{qq}", "850194007");
            //        //发送邮件
            //        DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl,
            //            siteConfig.emailusername,
            //            DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring),
            //            siteConfig.emailnickname,
            //            siteConfig.emailfrom,
            //            model.email,
            //            mailTitle, mailContent);
            //    }
            //}
            if (bll.Update(model))
            {
                AddAdminLog(DTEnums.ActionEnum.Reply.ToString(), "回复" + channel_name + "频道评论ID:" + model.id); //记录日志
            }
            else
            {
                return new SaveModel
                {
                    msg = "保存过程中发生错误！",
                    status = 0
                };
            }
            return new SaveModel
            {
                msg = "评论回复成功！",
                status = 1
            };
        }
        #endregion
        #endregion

        #region Tags标签
        #region 数据绑定
        public DataTable TagsBind(string _strWhere, string _orderby, out int totalCount, int page = 1, int pageSize = 10)
        {
            BLL.article_tags bll = new BLL.article_tags();
            DataTable resultlist = bll.GetList(pageSize, page, _strWhere, _orderby, out totalCount).Tables[0];
            return resultlist;
        }
        #endregion

        public JsonResult TagsDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.article_tags bll = new BLL.article_tags();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除Tags标签成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        public JsonResult TagsRed(List<int> ids)
        {
            BLL.article_tags bll = new BLL.article_tags();
            foreach (int id in ids)
            {
                bll.UpdateFile("id=" + id, "is_red=1");
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "设置推荐"); //记录日志
            return Json(new { status = 1, msg = "设置推荐成功！" });
        }

        public SaveModel TagsSave(string _action, int _id, Model.article_tags t)
        {
            BLL.article_tags bll = new BLL.article_tags();

            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            if (!string.IsNullOrEmpty(t.seo_keywords))
            {
                t.seo_keywords = t.seo_keywords.Replace("，", ",");
            }
            t.is_red = DTRequest.GetFormString("is_red").Contains("true") ? 1 : 0;

            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("sys_article_tags", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.article_tags model = bll.Get(_id);
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "修改Tags标签:" + model.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改Tags标签成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("sys_article_tags", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加Tags标签:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加Tags标签成功！",
                    status = 1
                };
            }
        }

        #region 赋值操作
        public Model.article_tags TagsInfo(int _id)
        {
            BLL.article_tags bll = new BLL.article_tags();
            Model.article_tags model = bll.Get(_id);
            return model;
        }
        #endregion
        #endregion

        #region 站点管理
        #region 数据绑定
        public Page<Model.sites> SiteBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.sites bll = new BLL.sites();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult SiteDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.sites bll = new BLL.sites();
            foreach (int id in ids)
            {
                //检查该分类下是否还有频道
                int channelCount = int.Parse(new BLL.site_channel().GetCount("count(*)", "site_id=" + id));
                if (channelCount > 0)
                {
                    errorCount += 1;
                    continue;
                }
                Model.sites model = bll.Get(id);
                //删除成功后对应的目录及文件
                if (bll.Delete(id))
                {
                    sucCount += 1;
                    Utils.DeleteDirectory(siteConfig.webpath + DTKeys.DIRECTORY_REWRITE_HTML + "/" + model.build_path);
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除站点成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 绑定网点
        public List<SelectListItem> SiteTreeBind(string _strWhere, string _strOrder)
        {
            BLL.sites bll = new BLL.sites();
            List<Model.sites> role_list = bll.GetModelList(0, _strWhere, "title,id", _strOrder);
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (Model.sites item in role_list)
            {
                list.Add(new SelectListItem() { Text = item.title, Value = item.id.ToString() });
            }
            return list;
        }

        #region 赋值操作
        public Model.sites SiteInfo(int _id)
        {
            BLL.sites bll = new BLL.sites();
            Model.sites model = bll.Get(_id);
            return model;
        }
        #endregion

        //保存
        public SaveModel SiteSave(string _action, int _id, Model.sites t)
        {
            BLL.sites bll = new BLL.sites();

            t.is_default = DTRequest.GetFormString("is_default").Contains("true") ? 1 : 0;
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;
            t.bdsend = DTRequest.GetFormString("bdsend").Contains("true") ? 1 : 0;
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            t.seo_description = Utils.DropHTML(t.seo_description);
            t.templet_path = t.build_path;
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("sys_site_manage", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.sites model = bll.Get(_id);
                if (model.logo != t.logo)
                {
                    FileHelper.DeleteFile(model.logo);
                }
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改站点:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改站点信息成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("sys_site_manage", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加站点:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加站点信息成功！",
                    status = 1
                };
            }
        }
        #endregion
        #endregion

        #region 频道管理
        #region 绑定类别
        public List<SelectListItem> ChannelTreeBind(string _strWhere, string _strOrder)
        {
            BLL.site_channel bll = new BLL.site_channel();
            List<Model.site_channel> role_list = bll.GetModelList(0, _strWhere, "title,id", _strOrder);
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (Model.site_channel item in role_list)
            {
                list.Add(new SelectListItem() { Text = item.title, Value = item.id.ToString() });
            }
            return list;
        }
        public List<SelectListItem> ChannelBind(string _strWhere, string _strOrder)
        {
            BLL.site_channel bll = new BLL.site_channel();
            List<Model.site_channel> role_list = bll.GetModelList(0, _strWhere, "title,name", _strOrder);
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (Model.site_channel item in role_list)
            {
                list.Add(new SelectListItem() { Text = item.title, Value = item.name });
            }
            return list;
        }
        #endregion

        public JsonResult ChannelDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.site_channel bll = new BLL.site_channel();
            foreach (int id in ids)
            {
                Model.site_channel model = bll.Get(id);
                if (bll.Delete(id))
                {
                    sucCount += 1;
                    //删除URL配置
                    new BLL.url_rewrite().Remove("channel", model.name);
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除频道成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 数据绑定
        public Page<Model.site_channel> ChannelBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.site_channel bll = new BLL.site_channel();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }

        public List<Model.site_channel> ChannelBind(int _site_id, string _strOrder)
        {
            BLL.site_channel bll = new BLL.site_channel();
            List<Model.site_channel> model = bll.GetModelList(0, "site_id=" + _site_id, "", _strOrder);
            return model;
        }
        #endregion

        #region 赋值操作
        public Model.site_channel ChannelInfo(int _id)
        {
            BLL.site_channel bll = new BLL.site_channel();
            Model.site_channel model = bll.GetModel(_id);
            return model;
        }
        #endregion

        #region 返回页面继承类
        private string GetInherit(string page_type)
        {
            string result = "";
            switch (page_type)
            {
                case "index":
                    result = "DTcms.Web.Mvc.UI.Page.article";
                    break;
                case "category":
                    result = "DTcms.Web.Mvc.UI.Page.category";
                    break;
                case "list":
                    result = "DTcms.Web.Mvc.UI.Page.article_list";
                    break;
                case "detail":
                    result = "DTcms.Web.Mvc.UI.Page.article_show";
                    break;
            }
            return result;
        }
        #endregion

        //保存
        public SaveModel ChannelSave(string _action, int _id, Model.site_channel t)
        {
            BLL.site_channel bll = new BLL.site_channel();

            #region 字段赋值
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;
            t.is_albums = DTRequest.GetFormString("is_albums").Contains("true") ? 1 : 0;
            t.is_zhuanti = DTRequest.GetFormString("is_zhuanti").Contains("true") ? 1 : 0;
            t.is_attach = DTRequest.GetFormString("is_attach").Contains("true") ? 1 : 0;
            t.is_spec = DTRequest.GetFormString("is_spec").Contains("true") ? 1 : 0;
            t.is_comment = DTRequest.GetFormString("is_comment").Contains("true") ? 1 : 0;
            t.is_attribute = DTRequest.GetFormString("is_attribute").Contains("true") ? 1 : 0;
            t.is_recycle = DTRequest.GetFormString("is_recycle").Contains("true") ? 1 : 0;
            t.is_type = Utils.StrToInt(t.is_type.ToString(), 0);
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);

            #region SEO优化
            t.seo_title = DTRequest.GetFormString("seo_title");
            t.seo_keywords = DTRequest.GetFormString("seo_keywords").Replace("，", ",");
            t.seo_description = DTRequest.GetFormString("seo_description");
            #endregion

            #endregion
            #region 保存URL配置
            BLL.url_rewrite urlBll = new BLL.url_rewrite();
            urlBll.Remove("channel", t.name); //先删除旧的
            string[] itemTypeArr = DTRequest.GetFormValues("item_type");
            string[] itemNameArr = DTRequest.GetFormValues("item_name");
            string[] itemPageArr = DTRequest.GetFormValues("item_page");
            string[] itemTempletArr = DTRequest.GetFormValues("item_templet");
            string[] itemPageSizeArr = DTRequest.GetFormValues("item_pagesize");
            string[] itemRewriteArr = DTRequest.GetFormValues("item_rewrite");
            if (itemTypeArr != null && itemNameArr != null && itemPageArr != null && itemTempletArr != null && itemPageSizeArr != null && itemRewriteArr != null)
            {
                int len = itemTypeArr.Length;
                if (itemNameArr.Length == len && itemPageArr.Length == len && itemTempletArr.Length == len && itemPageSizeArr.Length == len)
                {
                    Model.url_rewrite urlModel;
                    //获取网站名称
                    Model.sites modelt = new BLL.sites().Get(t.site_id);
                    //遍历
                    for (int i = 0; i < itemTypeArr.Length; i++)
                    {
                        urlModel = new Model.url_rewrite();
                        urlModel.name = itemNameArr[i];
                        urlModel.type = itemTypeArr[i];
                        urlModel.page = itemPageArr[i];
                        urlModel.inherit = GetInherit(urlModel.type);
                        urlModel.templet = itemTempletArr[i];
                        if (Utils.StrToInt(itemPageSizeArr[i], 0) > 0)
                        {
                            urlModel.pagesize = itemPageSizeArr[i];
                        }
                        urlModel.site = modelt.build_path;
                        urlModel.channel = t.name;

                        List<Model.url_rewrite_item> itemLs = new List<Model.url_rewrite_item>();
                        string[] urlRewriteArr = itemRewriteArr[i].Split('&'); //分解URL重写字符串
                        for (int j = 0; j < urlRewriteArr.Length; j++)
                        {
                            string[] urlItemArr = urlRewriteArr[j].Split(',');
                            if (urlItemArr.Length == 3)
                            {
                                itemLs.Add(new Model.url_rewrite_item { path = urlItemArr[0], pattern = urlItemArr[1], querystring = urlItemArr[2] });
                            }
                        }
                        urlModel.url_rewrite_items = itemLs;
                        urlBll.Add(urlModel);
                    }
                }
            }
            #endregion

            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                Model.site_channel model = bll.GetModel(_id);
                ChkAdminLevel("sys_channel_manage", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                #region 图片缩略图
                Model.site_channel_thum tmodel = null;
                t.channel_thums = new List<Model.site_channel_thum>();
                for (int i = 1; i <= 2; i++)
                {
                    tmodel = new Model.site_channel_thum();
                    string tid = "hidId_" + i.ToString();
                    string title = "hidTitle_" + i.ToString();
                    string class_id = "hidClassId_" + i.ToString();
                    string typeid = "type_id_" + i.ToString();
                    string width = "Width_" + i.ToString();
                    string is_lock = "is_lock_" + i.ToString();
                    string height = "Height_" + i.ToString();
                    //如果Html的Checkbox控件加入了Value属性,选中状态会把value内容传过来而不是true
                    tmodel.id = Utils.StrToInt(DTRequest.GetFormString(tid), 0);
                    tmodel.title = DTRequest.GetFormString(title);
                    tmodel.class_id = Utils.StrToInt(DTRequest.GetFormString(class_id), 0);
                    tmodel.typeid = Utils.StrToInt(DTRequest.GetFormString(typeid), 0);
                    tmodel.width = Utils.StrToInt(DTRequest.GetFormString(width), 0);
                    tmodel.height = Utils.StrToInt(DTRequest.GetFormString(height), 0);
                    tmodel.is_lock = DTRequest.GetFormString(is_lock).Contains("true") ? 1 : 0;
                    tmodel.channel_id = _id;
                    t.channel_thums.Add(tmodel);
                }
                #endregion
                #region 修改频道扩展字段
                BLL.article_attribute_field bll_field = new BLL.article_attribute_field();
                DataTable dt = bll_field.GetList(0, "", "sort_id asc,id desc").Tables[0];
                List<Model.site_channel_field> ls = new List<Model.site_channel_field>();
                foreach (DataRow item in dt.Rows)
                {
                    string FieldId = "cblAttributeField_" + item["id"];
                    if (DTRequest.GetFormValues(FieldId) != null)
                    {
                        ls.Add(new Model.site_channel_field { channel_id = t.id, field_id = Utils.ObjToInt(item["id"]) });
                    }
                }
                t.channel_fields = ls;
                #endregion
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改频道:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改频道成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("sys_channel_manage", DTEnums.ActionEnum.Add.ToString()); //检查权限
                #region 图片缩略图
                Model.site_channel_thum tmodel = null;
                t.channel_thums = new List<Model.site_channel_thum>();
                for (int i = 1; i <= 2; i++)
                {
                    tmodel = new Model.site_channel_thum();
                    string tid = "hidId_" + i.ToString();
                    string title = "hidTitle_" + i.ToString();
                    string class_id = "hidClassId_" + i.ToString();
                    string typeid = "type_id_" + i.ToString();
                    string width = "Width_" + i.ToString();
                    string is_lock = "is_lock_" + i.ToString();
                    string height = "Height_" + i.ToString();
                    tmodel.title = DTRequest.GetFormString(title);
                    tmodel.class_id = Utils.StrToInt(DTRequest.GetFormString(class_id), 0);
                    tmodel.typeid = Utils.StrToInt(DTRequest.GetFormString(typeid), 0);
                    tmodel.width = Utils.StrToInt(DTRequest.GetFormString(width), 0);
                    tmodel.height = Utils.StrToInt(DTRequest.GetFormString(height), 0);
                    tmodel.is_lock = DTRequest.GetFormString(is_lock).Contains("true") ? 1 : 0;
                    t.channel_thums.Add(tmodel);
                }
                #endregion
                #region 添加频道扩展字段
                BLL.article_attribute_field bll_field = new BLL.article_attribute_field();
                DataTable dt = bll_field.GetList(0, "", "sort_id asc,id desc").Tables[0];
                List<Model.site_channel_field> ls = new List<Model.site_channel_field>();
                foreach (DataRow item in dt.Rows)
                {
                    string FieldId = "cblAttributeField_" + item["id"];
                    if (DTRequest.GetFormValues(FieldId) != null)
                    {
                        ls.Add(new Model.site_channel_field { field_id = Utils.ObjToInt(item["id"]) });
                    }
                }
                t.channel_fields = ls;
                #endregion
                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加频道:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加频道成功！",
                    status = 1
                };
            }
        }
        #endregion

        #region 扩展字段管理
        #region 绑定扩展字段
        public List<Model.article_attribute_field> AttributeBind(string _strWhere, string _orderby)
        {
            BLL.article_attribute_field bll = new BLL.article_attribute_field();
            return bll.GetModelList(0, _strWhere, "", _orderby);
        }
        #endregion

        #region 数据绑定
        public Page<Model.article_attribute_field> AttributeBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.article_attribute_field bll = new BLL.article_attribute_field();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult AttributeDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.article_attribute_field bll = new BLL.article_attribute_field();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除扩展字段成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.article_attribute_field AttributeInfo(int _id)
        {
            BLL.article_attribute_field bll = new BLL.article_attribute_field();
            Model.article_attribute_field model = bll.Get(_id);
            return model;
        }
        #endregion

        //保存
        public SaveModel AttributeSave(string _action, int _id, Model.article_attribute_field t)
        {
            BLL.article_attribute_field bll = new BLL.article_attribute_field();
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            t.is_required = DTRequest.GetFormString("is_required").Contains("true") ? 1 : 0;
            t.is_password = DTRequest.GetFormString("is_password").Contains("true") ? 1 : 0;
            t.is_html = DTRequest.GetFormString("is_html").Contains("true") ? 1 : 0;
            t.data_length = Utils.StrToInt(t.data_length.ToString(), 0);
            t.data_place = Utils.StrToInt(t.data_place.ToString(), 0);

            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                Model.article_attribute_field model = bll.Get(_id);
                ChkAdminLevel("sys_channel_field", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                t.name = model.name;
                if (model.is_sys == 1)
                {
                    t.control_type = model.control_type;
                }
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改扩展字段:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "修改扩展字段成功！", status = 1 };
            }
            else //添加
            {
                ChkAdminLevel("sys_channel_field", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加扩展字段:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "添加扩展字段成功！", status = 1 };
            }
        }
        #endregion

        #region 会员管理
        #region 消费记录
        #region 数据绑定
        public Page<Model.user_amount_log> AmountLogBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.user_amount_log bll = new BLL.user_amount_log();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult AmountLogDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.user_amount_log bll = new BLL.user_amount_log();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除消息记录成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion

        #region 会员组管理
        public JsonResult GroupDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.user_groups bll = new BLL.user_groups();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除用户组成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.user_groups GroupInfo(int _id)
        {
            BLL.user_groups bll = new BLL.user_groups();
            Model.user_groups model = bll.Get(_id);
            return model;
        }
        #endregion

        //保存
        public SaveModel GroupSave(string _action, int _id, Model.user_groups t)
        {
            BLL.user_groups bll = new BLL.user_groups();
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 1 : 0;
            t.is_default = DTRequest.GetFormString("is_default").Contains("true") ? 1 : 0;
            t.is_upgrade = DTRequest.GetFormString("is_upgrade").Contains("true") ? 1 : 0;
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("user_group", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.user_groups model = bll.Get(_id);
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改用户组:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改用户组成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("user_group", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加用户组:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加会员组成功！",
                    status = 1
                };
            }
        }

        #region 绑定组别
        public List<SelectListItem> GroupTreeBind(string strWhere)
        {
            BLL.user_groups bll = new BLL.user_groups();
            List<Model.user_groups> groups_list = bll.GetModelList(0, string.Empty, "title,id", "grade asc,id asc");
            List<SelectListItem> groupListItems = new List<SelectListItem>();
            foreach (Model.user_groups item in groups_list)
            {
                groupListItems.Add(new SelectListItem() { Text = item.title, Value = item.id.ToString() });
            }
            return groupListItems;
        }
        #endregion
        #endregion

        #region 邮件模板
        #region 数据绑定
        public Page<Model.mail_template> MailBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.mail_template bll = new BLL.mail_template();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult MailDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.mail_template bll = new BLL.mail_template();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除邮件模板成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.mail_template MailInfo(int _id)
        {
            BLL.mail_template bll = new BLL.mail_template();
            Model.mail_template model = bll.Get(_id);
            return model;
        }
        #endregion

        //保存
        public SaveModel MailSave(string _action, int _id, Model.mail_template t)
        {
            BLL.mail_template bll = new BLL.mail_template();
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("user_mail_template", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.mail_template model = bll.Get(_id);
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改邮件模板:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改邮件模板成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("user_mail_template", DTEnums.ActionEnum.Add.ToString()); //检查权限

                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加邮件模板:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加邮件模板成功！",
                    status = 1
                };
            }
        }
        #endregion

        #region 消息管理
        #region 数据绑定
        public Page<Model.user_message> MessageBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.user_message bll = new BLL.user_message();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult MessageDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.user_message bll = new BLL.user_message();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除站内短消息成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.user_message MessageInfo(int _id)
        {
            BLL.user_message bll = new BLL.user_message();
            Model.user_message model = bll.Get(_id);
            return model;
        }
        #endregion

        //保存
        public SaveModel MessageSave(Model.user_message t)
        {
            BLL.user_message bll = new BLL.user_message();
            int i = 0;

            string[] arrUserName = t.accept_user_name.Split(',');
            if (arrUserName.Length > 0)
            {
                foreach (string username in arrUserName)
                {
                    if (new BLL.users().Exists(username))
                    {
                        t.accept_user_name = username;
                        if (bll.Add(t) < 1)
                        {
                            i++;
                        }
                        else
                        {

                        }
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "发送站内短消息，成功" + i + "条，失败" + (arrUserName.Length - i) + "条"); //记录日志

            if (i != 0)
            {
                return new SaveModel
                {
                    msg = "保存过程中发生错误！",
                    status = 0
                };
            }
            else
            {
                return new SaveModel
                {
                    msg = "发送站内短消息，成功" + i + "条，失败" + (arrUserName.Length - i) + "条！",
                    status = 1
                };
            }
        }
        #endregion

        #region OAuth第三方登录
        #region 数据绑定
        public Page<Model.user_oauth> OauthBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.user_oauth bll = new BLL.user_oauth();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }

        public Page<Model.oauth_app> OauthAppBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.oauth_app bll = new BLL.oauth_app();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult OauthDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.user_oauth bll = new BLL.user_oauth();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除OAuth授权成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        public JsonResult OauthAppDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.oauth_app bll = new BLL.oauth_app();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除OAuth配置成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion

        #region 积分记录
        #region 数据绑定
        public Page<Model.user_point_log> PointLogBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.user_point_log bll = new BLL.user_point_log();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult PointLogDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.user_point_log bll = new BLL.user_point_log();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除积分日志成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion

        #region 充值记录
        #region 数据绑定
        public Page<Model.user_recharge> RechargeBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.user_recharge bll = new BLL.user_recharge();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult RechargeDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.user_recharge bll = new BLL.user_recharge();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除充值记录成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 绑定支付方式
        public List<SelectListItem> RechargeTreeBind(string strWhere)
        {
            BLL.payment bll = new BLL.payment();
            List<Model.payment> groups_list = bll.GetModelList(0, string.Empty, "title,id", "sort_id asc,id asc");
            List<SelectListItem> paymentListItems = new List<SelectListItem>();
            foreach (Model.payment item in groups_list)
            {
                paymentListItems.Add(new SelectListItem() { Text = item.title, Value = item.id.ToString() });
            }
            return paymentListItems;
        }
        #endregion

        #region 支付方式
        public List<Model.payment> PaymentBind(string _strWhere, string _strOrder)
        {
            BLL.payment bll = new BLL.payment();
            var resultlist = bll.GetModelList(0, _strWhere, "", _strOrder);
            return resultlist;
        }
        public DataTable SitePaymentBind(string _strWhere, string _strOrder, out int totalCount, int page = 1, int pageSize = 10)
        {
            BLL.site_payment bll = new BLL.site_payment();
            return bll.GetList(pageSize, page, _strWhere, _strOrder, out totalCount).Tables[0];
        }
        public DataTable SiteOauthBind(string _strWhere, string _strOrder, out int totalCount, int page = 1, int pageSize = 10)
        {
            BLL.site_oauth bll = new BLL.site_oauth();
            return bll.GetList(pageSize, page, _strWhere, _strOrder, out totalCount).Tables[0];
        }
        public DataTable PaymentBind(int site_id, int payment_id)
        {
            BLL.payment bll = new BLL.payment();
            return bll.GetList(site_id, payment_id).Tables[0];
        }
        public DataTable OauthBind(int site_id, int oauth_id)
        {
            BLL.oauth_app bll = new BLL.oauth_app();
            return bll.GetList(site_id, oauth_id).Tables[0];
        }
        #endregion

        //保存
        public SaveModel RechargeSave(Model.user_recharge t)
        {
            Model.users userModel = new BLL.users().GetNmaeModel(t.user_name);
            BLL.user_recharge bll = new BLL.user_recharge();
            if (userModel == null)
            {
                return new SaveModel
                {
                    msg = "用户不存在！",
                    status = 0
                };
            }
            t.user_id = userModel.id;
            t.user_name = userModel.user_name;
            t.recharge_no = "R" + t.recharge_no; //订单号R开头为充值订单
            t.status = 1;
            t.add_time = DateTime.Now;
            t.complete_time = DateTime.Now;
            if (bll.Recharge(t))
            {
                AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "给会员：" + t.user_name + "，充值:" + t.amount + "元"); //记录日志
            }
            else
            {
                return new SaveModel
                {
                    msg = "保存过程中发生错误！",
                    status = 0
                };
            }
            return new SaveModel
            {
                msg = "会员充值成功！",
                status = 1
            };
        }
        #endregion

        #region 短信模板
        #region 数据绑定
        public Page<Model.sms_template> SmsBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.sms_template bll = new BLL.sms_template();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        //保存
        public SaveModel SmsSave(string _action, int _id, Model.sms_template t)
        {
            BLL.sms_template bll = new BLL.sms_template();

            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("user_sms_template", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                t.id = _id;
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改短信模板:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改短信模板成功！",
                    status = 1
                };
            }
            else
            {
                ChkAdminLevel("user_sms_template", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加短信模板:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加短信模板成功！",
                    status = 1
                };
            }
        }

        public JsonResult SmsDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.sms_template bll = new BLL.sms_template();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除短信模板成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.sms_template SmsInfo(int _id)
        {
            BLL.sms_template bll = new BLL.sms_template();
            Model.sms_template model = bll.Get(_id);
            return model;
        }
        #endregion
        #endregion

        #region 会员管理
        #region 数据绑定
        public Page<Model.users> UserBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.users bll = new BLL.users();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult UserAudit(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.users bll = new BLL.users();
            foreach (int id in ids)
            {
                if (bll.UpdateField(id, "status=0") > 0)
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Audit.ToString(), "审核会员成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "审核通过" + sucCount + "条，失败" + errorCount + "条！" });
        }

        public JsonResult UserDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.users bll = new BLL.users();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除用户" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.userconfig UserConfigInfo()
        {
            BLL.userconfig bll = new BLL.userconfig();
            Model.userconfig model = bll.loadConfig(false);
            return model;
        }
        #endregion

        //提交发送
        public SaveModel UserConfigSave(Model.userconfig t)
        {
            BLL.userconfig bll = new BLL.userconfig();
            Model.userconfig model = bll.loadConfig(false);
            try
            {
                t.regverify = DTRequest.GetFormString("regverify").Contains("true") ? 1 : 0;
                t.mobilelogin = DTRequest.GetFormString("mobilelogin").Contains("true") ? 1 : 0;
                t.emaillogin = DTRequest.GetFormString("emaillogin").Contains("true") ? 1 : 0;
                t.regrules = DTRequest.GetFormString("regrules").Contains("true") ? 1 : 0;
                t.articlelikelogin = DTRequest.GetFormString("articlelikelogin").Contains("true") ? 1 : 0;

                bll.saveConifg(t);
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改用户配置信息"); //记录日志
                return new SaveModel
                {
                    msg = "修改用户配置成功！",
                    status = 1
                };
            }
            catch (Exception)
            {
                return new SaveModel
                {
                    msg = "文件写入失败，请检查是否有权限！",
                    status = 0
                };
            }
        }

        #region 赋值操作
        public Model.users UserInfo(int _id)
        {
            BLL.users bll = new BLL.users();
            Model.users model = bll.Get(_id);
            if (!string.IsNullOrEmpty(model.password))
            {
                model.password = defaultpassword;
            }
            return model;
        }
        #endregion

        //保存
        public SaveModel UserSave(string _action, int _id, Model.users t)
        {
            BLL.users bll = new BLL.users();
            if (t.nick_name == "")
            {
                t.nick_name = t.user_name;
            }
            DateTime _birthday = DateTime.Now;
            if (DateTime.TryParse(t.birthday.ToString(), out _birthday))
            {
                t.birthday = _birthday;
            }
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("user_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.users model = bll.Get(_id);
                //判断密码是否更改
                if (t.password != defaultpassword)
                {
                    //获取用户已生成的salt作为密钥加密
                    t.password = DESEncrypt.Encrypt(t.password, model.salt);
                }
                else
                {
                    t.password = model.password;
                }
                t.reg_ip = model.reg_ip;
                t.site_id = model.site_id;
                t.salt = model.salt;
                t.reg_time = model.reg_time;
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改用户:" + t.user_name); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改会员成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("user_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
                //检测用户名是否重复
                if (bll.Exists(t.user_name))
                {
                    return new SaveModel
                    {
                        msg = "用户名重复！",
                        status = 0
                    };
                }
                //获得6位的salt加密字符串
                t.salt = Utils.GetCheckCode(6);
                //以随机生成的6位字符串做为密钥加密
                t.password = DESEncrypt.Encrypt(t.password, t.salt);
                t.reg_time = DateTime.Now;
                t.reg_ip = DTRequest.GetIP();
                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加用户:" + t.user_name); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加会员成功！",
                    status = 1
                };
            }
        }
        #endregion
        #endregion

        #region 控制面板
        #region URL配置管理
        #region 绑定数据
        public List<Model.url_rewrite> UrlRewriteBind(int _site, int _channel, string _type)
        {
            string siteName = new BLL.sites().GetTitle(_site);
            string channelNmae = new BLL.site_channel().GetChannelName(_channel);
            List<Model.url_rewrite> list = new BLL.url_rewrite().GetList(siteName, channelNmae, _type);
            return list;
        }
        #endregion
        public JsonResult UrlRewriteDelete(List<string> ids)
        {
            BLL.url_rewrite bll = new BLL.url_rewrite();
            foreach (string item in ids)
            {
                string urlName = item;
                if (!string.IsNullOrEmpty(urlName))
                {
                    AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除URL配置信息 name：" + urlName); //记录日志
                    bll.Remove("name", urlName);
                }
            }
            return Json(new { status = 1, msg = "URL配置删除成功！" });
        }
        #region 绑定频道页类型
        public List<SelectListItem> TypeBind()
        {
            List<SelectListItem> typeSelectItems = new List<SelectListItem>()
            {
                 new SelectListItem(){ Text="所有类型", Value=""},
                 new SelectListItem(){ Text="首页", Value="index"},
                 new SelectListItem(){ Text="列表页", Value="list"},
                 new SelectListItem(){ Text="栏目页", Value="category"},
                 new SelectListItem(){ Text="详细页", Value="detail"},
                 new SelectListItem(){ Text="插件页", Value="plugin"},
                 new SelectListItem(){ Text="其他页", Value="other"}
            };
            return typeSelectItems;
        }
        #endregion
        #region 赋值操作
        public Model.url_rewrite UrlRewriteInfo(string _urlName)
        {
            BLL.url_rewrite bll = new BLL.url_rewrite();
            Model.url_rewrite model = bll.GetInfo(_urlName);
            return model;
        }
        #endregion
        public SaveModel UrlRewriteSave(string name, string action, Model.url_rewrite t)
        {
            BLL.url_rewrite bll = new BLL.url_rewrite();

            //添加URL重写节点
            List<Model.url_rewrite_item> items = new List<Model.url_rewrite_item>();
            string[] itemPathArr = DTRequest.GetFormValues("itemPath");
            string[] itemPatternArr = DTRequest.GetFormValues("itemPattern");
            string[] itemQuerystringArr = DTRequest.GetFormValues("itemQuerystring");
            if (itemPathArr != null && itemPatternArr != null && itemQuerystringArr != null)
            {
                for (int i = 0; i < itemPathArr.Length; i++)
                {
                    items.Add(new Model.url_rewrite_item { path = itemPathArr[i], pattern = itemPatternArr[i], querystring = itemQuerystringArr[i] });
                }
            }
            t.url_rewrite_items = items;
            if (!string.IsNullOrEmpty(t.channel))
            {
                var modelt = new BLL.site_channel().GetModel(new { name = t.channel });
                if (modelt != null)
                {
                    var site = new BLL.sites().Get(modelt.site_id);
                    if (site != null)
                    {
                        t.site = site.build_path;
                    }
                }
            }
            if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("sys_url_rewrite", DTEnums.ActionEnum.Edit.ToString()); //检查权限

                if (bll.Edit(t))
                {

                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改URL配置信息:" + t.name); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "修改URL配置成功！", status = 1 };
            }
            else //添加
            {
                ChkAdminLevel("sys_url_rewrite", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (t.page.IndexOf(".") < 0)
                {
                    t.page += ".cshtml";
                }
                if (t.inherit.IndexOf(".") < 0)
                {
                    t.inherit = "DTcms.Web.Mvc.Areas.Web.Controllers." + t.inherit;
                }
                if (t.templet.IndexOf(".") < 0)
                {
                    t.templet += ".cshtml";
                }
                if (bll.Add(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加URL配置信息:" + t.name); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "添加URL配置成功！", status = 1 };
            }
        }
        #endregion
        #region 模板管理
        #region 数据绑定
        protected string buildPath = string.Empty;
        #region 读取模板配置信息
        /// <summary>
        /// 从模板说明文件中获得模板说明信息
        /// </summary>
        /// <param name="xmlPath">模板路径(不包含文件名)</param>
        /// <returns>模板说明信息</returns>
        private Model.template GetInfo(string xmlPath)
        {
            ///存放关于信息的文件 about.xml是否存在,不存在返回空串
            if (!System.IO.File.Exists(xmlPath + @"\about.xml"))
            {
                return null;
            }
            try
            {
                return (Model.template)SerializationHelper.Load(typeof(Model.template), xmlPath + @"\about.xml");
            }
            catch
            {
                return null;
            }
        }
        #endregion
        public DataTable TempletBind(int _site_id, out DataTable dtNew)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("skinname", Type.GetType("System.String"));
            dt.Columns.Add("version", Type.GetType("System.String"));
            dt.Columns.Add("preview", Type.GetType("System.String"));
            dt.Columns.Add("name", Type.GetType("System.String"));
            dt.Columns.Add("demo", Type.GetType("System.String"));
            dt.Columns.Add("img", Type.GetType("System.String"));
            dt.Columns.Add("author", Type.GetType("System.String"));
            dt.Columns.Add("description", Type.GetType("System.String"));
            dt.Columns.Add("website", Type.GetType("System.String"));
            dt.Columns.Add("createdate", Type.GetType("System.String"));
            dt.Columns.Add("apply", Type.GetType("System.Int32"));

            DirectoryInfo dirInfo = new DirectoryInfo(Utils.GetMapPath("~/templates/"));
            foreach (DirectoryInfo dir in dirInfo.GetDirectories())
            {
                DataRow dr = dt.NewRow();
                Model.template model = GetInfo(dir.FullName);
                if (model != null)
                {
                    dr["skinname"] = dir.Name;  //文件夹名称
                    dr["version"] = model.version;  //模板版本
                    dr["preview"] = model.preview;  //缩略图
                    dr["name"] = model.name;    // 模板名称
                    dr["demo"] = model.demo;    // 演示地址
                    dr["img"] = "~/templates/" + dir.Name + "/about.png";   // 模板图片
                    dr["author"] = model.author;    //作者
                    dr["description"] = model.description;  //版本描述
                    dr["website"] = model.website;  //网站域名
                    dr["createdate"] = model.createdate;    //创建日期
                    dr["apply"] = model.apply;    //适应范围
                    dt.Rows.Add(dr);
                }
            }

            //获取站点信息
            Model.sites modelt = new BLL.sites().Get(_site_id);
            if (modelt != null)
            {
                ////重新筛选
                DataTable dtNew1 = dt.Clone();
                DataRow[] drArr = dt.Select(string.Format("skinname='{0}'", modelt.templet_path));
                //重新写入表
                for (int i = 0; i < drArr.Length; i++)
                {
                    dtNew1.ImportRow(drArr[i]);
                }
                dtNew = dtNew1;

                //复制新表
                DataTable dtNew2 = dt.Clone();
                DataRow[] oldArr = dt.Select(string.Format("apply={0} and skinname<>'{1}'", modelt.site_type.ToString(), modelt.templet_path));
                //重新写入表
                for (int i = 0; i < oldArr.Length; i++)
                {
                    dtNew2.ImportRow(oldArr[i]);
                }
                return dtNew2;
            }
            else
            {
                dtNew = new DataTable();
                return dt;
            }
        }
        #region 应用模板
        /// <summary>
        /// 应用模板
        /// </summary>
        /// <param name="skinName">要启用的模板</param>
        /// <param name="sitepath">正在使用的模板</param>
        private void MarkTemplates(string skinName, string sitepath)
        {
            var allUrls = SiteUrls.GetEffective(siteConfig.webpath, sitepath);
            if (allUrls == null)
            {
                return;
            }
            BLL.url_rewrite bll = new BLL.url_rewrite();
            //修改
            foreach (Model.url_rewrite model in allUrls)
            {
                if (!string.IsNullOrEmpty(model.site))
                {
                    model.site = skinName;
                    foreach (Model.url_rewrite_item item in model.url_rewrite_items)
                    {
                        item.querystring = item.querystring.Replace("&", "^");
                    }
                    bll.Edit(model);
                }
            }
        }

        /// <summary>
        /// 应用模板
        /// </summary>
        /// <param name="skinname">要启用的模板</param>
        /// <param name="site_id">站点Id</param>
        /// <returns></returns>
        public JsonResult TempletStart(string skinname, int site_id)
        {
            try
            {
                BLL.sites bll = new BLL.sites();
                Model.sites modelt = bll.Get(site_id);//获取站点信息
                if (modelt != null)
                {
                    string sitepath = modelt.templet_path;
                    if (modelt.inherit_id > 0)
                    {
                        sitepath = bll.GetBuildPath(modelt.inherit_id);
                    }
                    MarkTemplates(skinname, sitepath);
                    //清除当前网站有效URL缓存
                    CacheFactory.Cache().RemoveCache(DTKeys.CACHE_SITE_EFFECTIVE_URLS + "_" + modelt.build_path);
                    //清除站点缓存
                    bll.ClearAll();

                    //修改当前频道分类当前模板名
                    new BLL.sites().UpdateField(modelt.id, string.Format("templet_path = '{0}',build_path='{0}'", skinname));
                    AddAdminLog(DTEnums.ActionEnum.Build.ToString(), "生成模板:" + skinname);//记录日志
                    return Json(new { status = 1, msg = "应用模板成功！" });
                }
                else
                {
                    return Json(new { status = 0, msg = "应用模板失败！" });
                }
            }
            catch (Exception e)
            {
                return Json(new { status = 0, msg = "错误：" + e.Message });
            }
        }
        #endregion
        #endregion
        #endregion
        #region 系统参数设置
        #region 赋值操作
        public Model.siteconfig SysConfigInfo()
        {
            BLL.siteconfig bll = new BLL.siteconfig();
            Model.siteconfig model = bll.loadConfig(false);

            if (!string.IsNullOrEmpty(model.smspassword))
            {
                model.smspassword = defaultpassword;
            }
            if (!string.IsNullOrEmpty(model.emailpassword))
            {
                model.emailpassword = defaultpassword;
            }
            return model;
        }
        #endregion

        //提交发送
        public SaveModel SysConfigSave(Model.siteconfig t)
        {
            BLL.siteconfig bll = new BLL.siteconfig();
            Model.siteconfig model = bll.loadConfig(false);
            try
            {
                string managepath = t.webmanagepath;
                if (model.webmanagepath != managepath)
                {
                    new BLL.navigation().updateicon(model.webmanagepath, managepath);
                    t.webmanagepath = managepath;
                }
                t.emailport = Utils.StrToInt(t.emailport.ToString(), 25);
                //判断密码是否更改
                if (t.emailpassword != defaultpassword && !string.IsNullOrEmpty(t.emailpassword))
                {
                    t.emailpassword = DESEncrypt.Encrypt(t.emailpassword, model.sysencryptstring);
                }
                else
                {
                    t.emailpassword = model.emailpassword;
                }

                //判断密码是否更改
                if (t.smspassword != defaultpassword&&!string.IsNullOrEmpty(t.smspassword))
                {
                    t.smspassword = DESEncrypt.Encrypt(t.smspassword);
                }
                else
                {
                    t.smspassword = model.smspassword;
                }
                t.localpath = t.localpath.ToString().Replace("\\\\", "\\");
                //图片质量
                int quality = Utils.StrToInt(t.watermarkimgquality.ToString(), 80);
                if (quality < 10)
                {
                    quality = 10;
                }
                else if (quality > 100)
                {
                    quality = 100;
                }
                t.watermarkimgquality = quality;
                t.watermarktransparency = Utils.StrToInt(t.watermarktransparency.ToString(), 5);
                t.watermarkfontsize = Utils.StrToInt(t.watermarkfontsize.ToString(), 12);
                t.cachetime = Utils.StrToInt(t.cachetime.ToString(), 30);
                t.memberstatus = DTRequest.GetFormString("memberstatus").Contains("true") ? 1 : 0;
                t.commentstatus = DTRequest.GetFormString("commentstatus").Contains("true") ? 1 : 0;
                t.commentsemail = DTRequest.GetFormString("commentsemail").Contains("true") ? 1 : 0;
                t.logstatus = DTRequest.GetFormString("logstatus").Contains("true") ? 1 : 0;
                t.webstatus = DTRequest.GetFormString("webstatus").Contains("true") ? 1 : 0;
                t.emailssl = DTRequest.GetFormString("emailssl").Contains("true") ? 1 : 0;
                t.systemcache = DTRequest.GetFormString("systemcache").Contains("true") ? 1 : 0;

                bll.saveConifg(t);

                //更新上传脚本文件
                uploadjs(t);

                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改系统配置信息"); //记录日志
                return new SaveModel
                {
                    msg = "修改系统配置成功！",
                    status = 1
                };
            }
            catch (Exception ex)
            {
                return new SaveModel { msg = "文件写入失败，请检查文件夹权限！", status = 0 };
            }
        }
        #region 扩展方法
        /// <summary>
        /// 更新上传脚本文件
        /// </summary>
        /// <param name="model"></param>
        private void uploadjs(Model.siteconfig model)
        {
            //读取文件
            string content = FileHelper.ReadFile("/scripts/libs/js/uploader.js");
            if (!string.IsNullOrEmpty(content))
            {
                IList<object> list = new List<object>();
                list.Add(new
                {
                    title = "图片上传",
                    size = model.imgsize,
                    filetypes = model.imgextension,
                    mimeTypes = "." + model.imgextension.Replace(",", ",.")
                });
                list.Add(new
                {
                    title = "附件上传",
                    size = model.attachsize,
                    filetypes = model.attachextension,
                    mimeTypes = "." + model.attachextension.Replace(",", ",.")
                });
                list.Add(new
                {
                    title = "视频上传",
                    size = model.videosize,
                    filetypes = model.videoextension,
                    mimeTypes = "." + model.videoextension.Replace(",", ",.")
                });
                string json = JsonHelper.ObjectToJSON(list);
                content = Regex.Replace(content, @"var\supLoadParam\s=\s([\s\S]+?);", string.Format("var upLoadParam = {0};", json), RegexOptions.None);

                //保存上传JS文件
                FileHelper.WriteFile("/scripts/libs/js/uploader.js", content);
            }
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="FileName">文件路径</param>
        /// <returns>文本内容</returns>
        public string ReadFile(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            return string.Empty;
        }
        #endregion
        #endregion
        #region 缓存管理
        /// <summary>
        /// 输出缓存列表
        /// </summary>
        public DataTable SysCacheBind()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("i", Type.GetType("System.Int32"));
            dt.Columns.Add("name", Type.GetType("System.String"));
            int i = 0;
            //缓存前缀
            List<string> prefix = new List<string>();
            prefix.Add("sys_");
            prefix.Add("dt_");
            prefix.Add(siteConfig.cachekey);

            List<string> list = CacheFactory.Cache().GetAllCache(prefix);
            foreach (var t in list)
            {
                i++;
                DataRow row = dt.NewRow();
                row["i"] = i;
                row["name"] = t;
                dt.Rows.Add(row);
            }
            return dt;
        }

        public JsonResult SysCacheDelete(List<string> ids)
        {
            foreach (string item in ids)
            {
                CacheFactory.Cache().RemoveCache(item);
            }
            return Json(new { status = 1, msg = "缓存删除成功！" });
        }

        public JsonResult SysCacheDelAll()
        {
            CacheFactory.Cache().RemoveCache();
            return Json(new { status = 1, msg = "缓存删除成功！" });
        }
        #endregion
        #region 插件设置
        public JsonResult SysPluginUninstall(string ids)
        {
            string[] list = ids.Split(',');
            //插件目录
            string pluginPath = Utils.GetMapPath("/plugins");
            string script = string.Empty;
            BLL.plugin bll = new BLL.plugin();
            //查找列表
            foreach (string currDirName in list)
            {
                if (!string.IsNullOrEmpty(currDirName))
                {
                    //是否已安装
                    Model.plugin model = bll.GetInfo(pluginPath + currDirName + @"\");
                    if (model.isload == 1)
                    {
                        string currPath = pluginPath + currDirName + @"/bin/";
                        if (Directory.Exists(currPath))
                        {
                            string[] file = Directory.GetFiles(currPath);
                            foreach (string f in file)
                            {
                                FileInfo info = new FileInfo(f);
                                //复制DLL文件
                                if (info.Extension.ToLower() == ".dll" || info.Extension.ToLower() == ".xml")
                                {
                                    //删除站点目录下DLL文件
                                    string newFile = Utils.GetMapPath(siteConfig.webpath + @"bin/" + info.Name);
                                    if (System.IO.File.Exists(newFile))
                                    {
                                        System.IO.File.Delete(newFile);
                                    }
                                }
                            }
                        }
                        bool install = false;
                        //执行SQL语句
                        if (siteConfig.deltable == 0)
                        {
                            install = bll.ExeSqlStr(pluginPath + currDirName + @"\", @"plugin/uninstall");
                        }
                        if (!install)
                        {
                            //return Json(new { status = 0, msg = "执行SQL语句错误！" });
                        }
                        //删除URL映射
                        bll.RemoveNodes(pluginPath + currDirName + @"\", @"plugin/urls");
                        //删除后台导航记录
                        bll.RemoveMenuNodes(pluginPath + currDirName + @"\", @"plugin/menu");
                        //删除站点目录下的aspx文件
                        RemoveTemplates(currDirName);
                        //修改plugins节点
                        bll.UpdateNodeValue(pluginPath + currDirName + @"\", @"plugin/isload", "0");
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.UnLoad.ToString(), "卸载插件"); //记录日志
            return Json(new { status = 1, msg = "插件卸载成功！" });
        }

        public JsonResult SysPluginInstall(string ids)
        {
            string[] list = ids.Split(',');
            //插件目录
            string pluginPath = Utils.GetMapPath("/plugins/");
            string script = string.Empty;
            BLL.plugin bll = new BLL.plugin();
            //查找列表
            foreach (string currDirName in list)
            {
                if (!string.IsNullOrEmpty(currDirName))
                {
                    //是否未安装
                    Model.plugin model = bll.GetInfo(pluginPath + currDirName + @"\");
                    if (model.isload == 0)
                    {
                        //安装DLL
                        string currPath = pluginPath + currDirName + @"\bin\";
                        if (Directory.Exists(currPath))
                        {
                            string[] file = Directory.GetFiles(currPath);
                            foreach (string f in file)
                            {
                                FileInfo info = new FileInfo(f);
                                //复制DLL文件
                                if (info.Extension.ToLower() == ".dll" || info.Extension.ToLower() == ".xml")
                                {
                                    //移动到站点目录下
                                    string newFile = Utils.GetMapPath(siteConfig.webpath + @"bin\" + info.Name);
                                    System.IO.File.Copy(info.FullName, newFile, true);
                                }
                            }
                        }
                        //执行SQL语句
                        bool install = bll.ExeSqlStr(pluginPath + currDirName + @"\", @"plugin/install");
                        if (!install)
                        {
                            //return Json(new { status = 0, msg = "执行SQL语句错误！" });
                        }
                        //添加URL映射
                        bll.AppendNodes(pluginPath + currDirName + @"\", @"plugin/urls");
                        //添加后台导航记录
                        //bll.AppendMenuNodes(string.Format("{0}plugins/{1}/", siteConfig.webpath, currDirName), pluginPath + currDirName + @"\", @"plugin/menu", "sys_plugin_manage");
                        bll.AppendMenuNodes("", pluginPath + currDirName + @"\", @"plugin/menu", "sys_plugin_manage");
                        //生成模板
                        //遍历插件模板目录下的站点目录，生成模板
                        DirectoryInfo tempPath = new DirectoryInfo(pluginPath + currDirName + @"\templet\"); //插件模板目录实例
                        if (tempPath.Exists)
                        {
                            foreach (DirectoryInfo dirInfo in tempPath.GetDirectories())
                            {
                                //如果该站点目录存在则生成模板
                                if (Directory.Exists(Utils.GetMapPath(siteConfig.webpath + DTKeys.DIRECTORY_REWRITE_MVC + "/" + dirInfo.Name + "/")))
                                {
                                    bll.MarkTemplet(siteConfig.webpath, "plugins/" + currDirName + "/templet", dirInfo.Name, pluginPath + currDirName + @"\", @"plugin/urls", currDirName);
                                }
                            }
                        }
                        //修改plugins节点
                        bll.UpdateNodeValue(pluginPath + currDirName + @"\", @"plugin/isload", "1");
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Instal.ToString(), "安装插件"); //记录日志
            return Json(new { status = 1, msg = "插件安装成功！" });
        }

        public JsonResult SysPluginRemark(string ids)
        {
            string msg = string.Empty;
            string[] list = ids.Split(',');
            //插件目录
            string pluginPath = Utils.GetMapPath("/plugins/");
            BLL.plugin bll = new BLL.plugin();
            //查找列表
            foreach (string currDirName in list)
            {
                if (!string.IsNullOrEmpty(currDirName))
                {
                    //是否安装
                    Model.plugin model = bll.GetInfo(pluginPath + currDirName + @"\");
                    if (model.isload == 1)
                    {
                        //遍历插件模板目录下的站点目录
                        DirectoryInfo tempPath = new DirectoryInfo(Utils.GetMapPath("/plugins/" + currDirName + "/templet/")); //插件模板目录实例
                        if (tempPath.Exists)
                        {
                            foreach (DirectoryInfo dirInfo in tempPath.GetDirectories())
                            {
                                //如果该站点目录存在则生成模板
                                if (Directory.Exists(Utils.GetMapPath(siteConfig.webpath + DTKeys.DIRECTORY_REWRITE_MVC + "/" + dirInfo.Name + "/")))
                                {
                                    bll.MarkTemplet(siteConfig.webpath, "plugins/" + currDirName + "/templet", dirInfo.Name, pluginPath + currDirName + @"\", @"plugin/urls", currDirName);
                                }
                            }
                        }
                        msg = "生成模板成功！";
                    }
                    else
                    {
                        msg = "该插件尚未安装！";
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Build.ToString(), "生成插件模板"); //记录日志
            return Json(new { status = 1, msg = msg });
        }

        public List<Model.plugin> SysPluginBind()
        {
            List<Model.plugin> lt = new List<Model.plugin>();
            BLL.plugin bll = new BLL.plugin();
            return bll.GetList(Utils.GetMapPath("/plugins/"));
        }

        #region 删除生成的ASPX文件====
        private void RemoveTemplates(string dirName)
        {
            string fullPath = Utils.GetMapPath("/plugins/" + dirName + "/"); //插件目录物理路径
            DirectoryInfo tempPath = new DirectoryInfo(fullPath + @"templet\"); //插件模板目录实例
            XmlNodeList xnList = XmlHelper.ReadNodes(fullPath + DTKeys.FILE_PLUGIN_XML_CONFING, "plugin/urls");
            if (xnList.Count > 0)
            {
                foreach (XmlElement xe in xnList)
                {
                    if (xe.NodeType != XmlNodeType.Comment && xe.Name.ToLower() == "rewrite" && xe.Attributes["page"] != null)
                    {
                        if (xe.Attributes["name"] != null && xe.Attributes["type"] != null)
                        {
                            //遍历插件模板目录下的站点目录
                            if (tempPath.Exists)
                            {
                                foreach (DirectoryInfo dirInfo in tempPath.GetDirectories())
                                {
                                    //删除对应站点下的aspx文件
                                    FileHelper.DeleteFile(siteConfig.webpath + DTKeys.DIRECTORY_REWRITE_MVC + "/" + dirInfo.Name + "/" + xe.Attributes["page"].Value);
                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion
        #endregion
        #region 后台导航管理
        //数据绑定
        public DataTable SysNavigationBind()
        {
            BLL.navigation bll = new BLL.navigation();
            DataTable dt = bll.GetList(0, DTEnums.NavigationEnum.System.ToString());
            return dt;
        }


        public JsonResult SysNavigationDelete(List<int> ids)
        {
            BLL.navigation bll = new BLL.navigation();
            foreach (int id in ids)
            {
                bll.Delete(id);
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除导航菜单"); //记录日志
            return Json(new { status = 1, msg = "删除数据成功！" });
        }

        #region 赋值操作
        public Model.navigation SysNavigationInfo(int _id)
        {
            BLL.navigation bll = new BLL.navigation();
            Model.navigation model = bll.Get(_id);
            return model;
        }
        #endregion

        #region 绑定导航菜单
        public List<SelectListItem> SysNavigationTreeBind(string nav_type)
        {
            BLL.navigation bll = new BLL.navigation();
            DataTable dt = bll.GetList(0, nav_type);
            List<SelectListItem> parentList = new List<SelectListItem>();
            foreach (DataRow dr in dt.Rows)
            {
                string Id = dr["id"].ToString();
                int ClassLayer = int.Parse(dr["class_layer"].ToString());
                string Title = dr["title"].ToString();
                if (ClassLayer == 1)
                {
                    parentList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = Utils.StringOfChar(ClassLayer - 1, "　") + Title;
                    parentList.Add(new SelectListItem() { Text = Title, Value = Id });
                }
            }
            return parentList;
        }
        #endregion


        public SaveModel SysNavigationSave(string _action, int _id, Model.navigation t)
        {
            BLL.navigation bll = new BLL.navigation();
            //添加操作权限类型
            string action_type_str = string.Empty;
            foreach (KeyValuePair<string, string> kv in Utils.ActionType())
            {
                if (DTRequest.GetFormString("cblActiontype_" + kv.Key).Contains("true"))
                {
                    action_type_str += kv.Key + ",";
                }
            }
            t.action_type = Utils.DelLastComma(action_type_str);
            t.nav_type = DTEnums.NavigationEnum.System.ToString();
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;

            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("sys_navigation", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.navigation model = bll.Get(_id);
                if (model.is_sys == 0)
                {
                    int parentId = t.parent_id;
                    //如果选择的父ID不是自己,则更改
                    if (parentId != model.id)
                    {
                        t.parent_id = parentId;
                    }
                }
                else
                {
                    t.parent_id = model.parent_id;
                }
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "修改导航菜单:" + model.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改导航菜单成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("sys_navigation", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加导航菜单:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加导航菜单成功！",
                    status = 1
                };
            }
        }
        #endregion
        #region 生成静态页面
        #region 数据绑定
        public List<Model.site_channel> BuilderBind(int _site_id)
        {
            BLL.site_channel bll = new BLL.site_channel();
            string strWhere = string.Empty;
            if (_site_id != 0)
            {
                strWhere = "site_id=" + _site_id;
            }
            List<Model.site_channel> model = bll.GetModelList(0, strWhere, "", "sort_id asc,id desc");
            return model;
        }
        #endregion
        #endregion
        #region 角色列表
        #region 角色类型
        public List<SelectListItem> RoleTypeBind()
        {
            Model.manager model = GetAdminInfo();
            List<SelectListItem> roleList = new List<SelectListItem>();
            roleList.Add(new SelectListItem() { Text = "请选择类型...", Value = "" });
            if (model.role_type < 2)
            {
                roleList.Add(new SelectListItem() { Text = "超级用户", Value = "1" });
            }
            roleList.Add(new SelectListItem() { Text = "系统用户", Value = "2" });
            return roleList;
        }
        #endregion

        #region 角色类型
        public List<SelectListItem> ManagerRoleBind(int role_type)
        {
            BLL.manager_role bll = new BLL.manager_role();
            List<Model.manager_role> role_list = bll.GetModelList(0, string.Empty, "role_type,role_name,id", "");
            List<SelectListItem> list = new List<SelectListItem>();
            if (role_list.Count != 1)
            {
                list.Add(new SelectListItem() { Text = "请选择角色...", Value = "" });
            }
            foreach (Model.manager_role item in role_list)
            {
                if (item.role_type >= role_type)
                {
                    list.Add(new SelectListItem() { Text = item.role_name, Value = item.id.ToString() });
                }
            }
            return list;
        }
        #endregion

        #region 数据绑定
        public List<Model.manager_role> ManagerRoleBind(string _strWhere, string _strOrder)
        {
            BLL.manager_role bll = new BLL.manager_role();
            var resultlist = bll.GetModelList(0, _strWhere, "", _strOrder);
            return resultlist;
        }
        #endregion


        public JsonResult ManagerRoleDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.manager_role bll = new BLL.manager_role();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除管理角色" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.manager_role ManagerRoleInfo(int _id)
        {
            BLL.manager_role bll = new BLL.manager_role();
            Model.manager_role model = bll.GetModel(_id);
            return model;
        }
        #endregion


        public SaveModel ManagerRoleSave(string _action, int _id, string json, string role_name, int role_type)
        {
            BLL.manager_role bll = new BLL.manager_role();
            Model.manager_role model = new Model.manager_role();
            model.role_name = role_name;
            model.role_type = role_type;
            JObject jobject = JObject.Parse(json);
            JToken record = jobject["list"];
            //管理权限
            List<Model.manager_role_value> ls = new List<Model.manager_role_value>();
            foreach (JToken item in record)
            {
                JArray action_types = JArray.FromObject(item["action_type"]);
                foreach (JToken action in action_types)
                {
                    ls.Add(new Model.manager_role_value { nav_name = item["name"].ToString(), action_type = action.ToString() });
                }
            }
            model.manager_role_values = ls;

            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("manager_role", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                model.id = _id;

                if (bll.Update(model))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改管理角色:" + model.role_name); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改管理角色成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("sys_navigation", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Add(model) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加管理角色:" + model.role_name); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加管理角色成功！",
                    status = 1
                };
            }
        }
        #endregion
        #region 管理员管理
        #region 数据绑定
        public Page<Model.manager> ManagerBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.manager bll = new BLL.manager();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion


        public JsonResult ManagerDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.manager bll = new BLL.manager();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除管理员" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 赋值操作
        public Model.manager ManagerInfo(int _id)
        {
            BLL.manager bll = new BLL.manager();
            Model.manager model = bll.Get(_id);
            return model;
        }
        #endregion


        public SaveModel ManagerSave(string _action, int _id, Model.manager t)
        {
            BLL.manager bll = new BLL.manager();
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;
            t.role_type = new BLL.manager_role().GetModel(t.role_id).role_type;
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("manager_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                t.id = _id;
                Model.manager model = bll.Get(_id);
                t.salt = model.salt;
                t.user_name = model.user_name;
                //判断密码是否更改
                if (t.password != defaultpassword)
                {
                    //获取用户已生成的salt作为密钥加密
                    t.password = DESEncrypt.Encrypt(t.password, model.salt + DTKeys.SECURITY_CODE);
                }
                else
                {
                    t.password = model.password;
                }
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改管理员:" + t.user_name); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改管理员信息成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("manager_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
                //检测用户名是否重复
                if (bll.Exists(t.user_name))
                {
                    return new SaveModel
                    {
                        msg = "用户名重复！",
                        status = 0
                    };
                }
                t.add_time = DateTime.Now;
                //获得6位的salt加密字符串
                t.salt = Utils.GetCheckCode(6);
                //以随机生成的6位字符串做为密钥加密
                t.password = DESEncrypt.Encrypt(t.password, t.salt + DTKeys.SECURITY_CODE);
                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加管理员:" + t.user_name); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加管理员信息成功！",
                    status = 1
                };
            }
        }
        #endregion
        #region 管理日志
        #region 数据绑定
        public Page<Model.manager_log> ManagerLogBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.manager_log bll = new BLL.manager_log();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion


        public JsonResult ManagerLogDelete()
        {
            BLL.manager_log bll = new BLL.manager_log();
            int sucCount = bll.Delete("DATEDIFF(day, add_time, getdate()) > " + 7);
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除管理日志" + sucCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除日志" + sucCount + "条！" });
        }
        #endregion
        #region 修改管理员密码

        public JsonResult ManagerSave(Model.manager t)
        {
            BLL.manager bll = new BLL.manager();
            Model.manager model = GetAdminInfo();

            if (DESEncrypt.Encrypt(DTRequest.GetFormString("txtOldPassword"), model.salt + DTKeys.SECURITY_CODE) != model.password)
            {
                return Json(new { status = 0, msg = "旧密码不正确！" });
            }
            if (t.password != DTRequest.GetFormString("txtPassword1"))
            {
                return Json(new { status = 0, msg = "两次密码不一致！" });
            }
            model.password = DESEncrypt.Encrypt(t.password, model.salt + DTKeys.SECURITY_CODE);
            model.real_name = t.real_name;
            model.telephone = t.telephone;
            model.email = t.telephone;

            if (!bll.Update(model))
            {
                return Json(new { status = 0, msg = "保存过程中发生错误！" });
            }
            Session[DTKeys.SESSION_ADMIN_INFO] = null;
            return Json(new { status = 1, msg = "密码修改成功！" });
        }
        #endregion
        #region 模板文件管理
        public DataTable TempletFileBind(string skinName, string filepath, int areas)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("type", Type.GetType("System.String"));
            dt.Columns.Add("url", Type.GetType("System.String"));
            dt.Columns.Add("target", Type.GetType("System.String"));
            dt.Columns.Add("name", Type.GetType("System.String"));
            dt.Columns.Add("skinname", Type.GetType("System.String"));
            dt.Columns.Add("creationtime", Type.GetType("System.String"));
            dt.Columns.Add("updatetime", Type.GetType("System.String"));
            dt.Columns.Add("size", Type.GetType("System.String"));

            string fileurl = "/templates/" + skinName;
            if (areas == 1)
            {
                fileurl = "/Areas/Web/Views/" + skinName;
            }
            DirectoryInfo dirInfo = new DirectoryInfo(Utils.GetMapPath(@"" + fileurl + "/" + filepath));
            //获取目录
            foreach (DirectoryInfo dir in dirInfo.GetDirectories())
            {
                DataRow dr = dt.NewRow();
                dr["type"] = "folder";
                dr["url"] = string.Format("templet_file_list?skin={0}&filepath={1}{2}&areas={3}", skinName, filepath, dir.Name, areas);
                dr["target"] = "_self";
                dr["name"] = dir.Name;
                dr["skinname"] = skinName;
                dr["creationtime"] = dir.CreationTime;
                dr["updatetime"] = dir.LastWriteTime;
                dt.Rows.Add(dr);
            }
            //获取所有文件
            foreach (FileInfo file in dirInfo.GetFiles())
            {
                if (file.Name != "about.xml" && file.Name != "about.png")
                {
                    DataRow dr = dt.NewRow();
                    dr["type"] = "file";
                    switch (Utils.GetFileExt(file.Name))
                    {
                        case ".css":
                        case ".js":
                        case ".cshtml":
                            dr["type"] = "file";
                            dr["url"] = string.Format("../settings/templet_file_edit?path={0}&filename={1}{2}&areas={3}", skinName, filepath, file.Name, areas);
                            dr["target"] = "templateFrame";
                            break;
                        case ".gif":
                        case ".jpg":
                        case ".png":
                            dr["type"] = "img";
                            dr["url"] = string.Format("javascript:ballImages('/templates/{0}/{1}{2}')", skinName, filepath, file.Name);
                            dr["target"] = "_self";
                            break;
                        default:
                            dr["type"] = "file";
                            dr["url"] = "javascript:;";
                            dr["target"] = "_self";
                            break;
                    }
                    dr["name"] = file.Name;
                    dr["skinname"] = skinName;
                    dr["creationtime"] = file.CreationTime;
                    dr["size"] = Utils.CountSize(file.Length);
                    dr["updatetime"] = file.LastWriteTime;
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
        public SaveModel TempletFileSave(string filePath, string fileName, string txtContent)
        {
            string fileUrl = "/templates/" + filePath.Replace("..", "") + "/" + fileName;
            filePath = Utils.GetMapPath(@"/templates/" + filePath.Replace("..", "") + "/" + fileName);
            if (!System.IO.File.Exists(filePath))
            {
                return new SaveModel
                {
                    msg = "模板文件不存在！",
                    status = 0
                };
            }
            FileHelper.WriteFile(fileUrl, txtContent);
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改模板文件:" + fileName);//记录日志
            return new SaveModel
            {
                msg = "模板保存成功！",
                status = 1
            };
        }
        #endregion
        #endregion

        #region 订单
        #region 支付方式
        #region 数据绑定
        public List<SelectListItem> OrderPaymentBind(string _strWhere, string _orderby)
        {
            BLL.payment bll = new BLL.payment();
            List<Model.payment> resultlist = bll.GetModelList(0, _strWhere, "title,id", _orderby);
            List<SelectListItem> paymentListItems = new List<SelectListItem>();
            paymentListItems.Add(new SelectListItem() { Text = "请选择支付方式", Value = "" });
            foreach (Model.payment item in resultlist)
            {
                paymentListItems.Add(new SelectListItem() { Text = item.title, Value = item.id.ToString() });
            }
            return paymentListItems;
        }
        #endregion

        #region 赋值操作
        public Model.payment OrderPaymentinfo(int _id)
        {
            BLL.payment bll = new BLL.payment();
            Model.payment model = bll.Get(_id);
            return model;
        }
        public Model.site_payment SiteOrderPaymentinfo(int _id)
        {
            BLL.site_payment bll = new BLL.site_payment();
            Model.site_payment model = bll.Get(_id);
            return model;
        }
        public Model.site_oauth SiteOauthinfo(int _id)
        {
            BLL.site_oauth bll = new BLL.site_oauth();
            Model.site_oauth model = bll.Get(_id);
            return model;
        }
        public Model.oauth_app OauthAppinfo(int _id)
        {
            BLL.oauth_app bll = new BLL.oauth_app();
            Model.oauth_app model = bll.Get(_id);
            return model;
        }
        #endregion

        //保存
        public SaveModel OrderPaymentSave(string _action, int _id, Model.payment t)
        {
            BLL.payment bll = new BLL.payment();
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("order_payment", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.payment model = bll.Get(_id);

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改支付平台:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改支付平台成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("order_payment", DTEnums.ActionEnum.Add.ToString()); //检查权限

                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加支付平台:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加支付平台成功！",
                    status = 1
                };
            }
        }

        public SaveModel SiteOrderPaymentSave(string _action, int _id, Model.site_payment t)
        {
            BLL.site_payment bll = new BLL.site_payment();
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("order_payment", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.site_payment model = bll.Get(_id);

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改站点支付方式:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改站点支付方式成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("order_payment", DTEnums.ActionEnum.Add.ToString()); //检查权限

                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加站点支付方式:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加站点支付方式成功！",
                    status = 1
                };
            }
        }

        public SaveModel SiteOauthSave(string _action, int _id, Model.site_oauth t)
        {
            BLL.site_oauth bll = new BLL.site_oauth();
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("user_oauth", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.site_oauth model = bll.Get(_id);

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改站点OAuth:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改站点OAuth成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("user_oauth", DTEnums.ActionEnum.Add.ToString()); //检查权限

                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加站点OAuth:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加站点OAuth成功！",
                    status = 1
                };
            }
        }
        public SaveModel OauthAppSave(string _action, int _id, Model.oauth_app t)
        {
            BLL.oauth_app bll = new BLL.oauth_app();
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("user_oauth", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.oauth_app model = bll.Get(_id);

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改OAuth应用:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改OAuth应用成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("user_oauth", DTEnums.ActionEnum.Add.ToString()); //检查权限

                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加OAuth应用:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加OAuth应用成功！",
                    status = 1
                };
            }
        }

        public JsonResult SitePaymentDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.site_payment bll = new BLL.site_payment();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除支付方式成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        public JsonResult SiteOauthDelete(List<int> ids)
        {
            int sucCount = 0;
            int errorCount = 0;
            BLL.site_oauth bll = new BLL.site_oauth();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount += 1;
                }
                else
                {
                    errorCount += 1;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除OAuth列表成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }
        #endregion
        #region 订单管理
        #region 订单参数设置
        #region 赋值操作
        public Model.orderconfig OrderConfigInfo()
        {
            BLL.orderconfig bll = new BLL.orderconfig();
            Model.orderconfig model = bll.loadConfig(false);
            return model;
        }
        #endregion

        //提交发送
        public SaveModel OrderConfigSave(Model.orderconfig t)
        {
            BLL.orderconfig bll = new BLL.orderconfig();
            try
            {
                t.anonymous = DTRequest.GetFormString("anonymous").Contains("true") ? 1 : 0;
                bll.saveConifg(t);
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改订单配置信息"); //记录日志
                return new SaveModel
                {
                    msg = "修改订单配置成功！",
                    status = 1
                };
            }
            catch (Exception)
            {
                return new SaveModel
                {
                    msg = "文件写入失败，请检查是否有权限！",
                    status = 0
                };
            }
        }
        #endregion
        #endregion
        #region 物流配送
        #region 数据绑定
        public Page<Model.express> OrderExpressBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.express bll = new BLL.express();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public JsonResult OrderExpressDelete(List<int> ids)
        {
            BLL.express bll = new BLL.express();
            foreach (int id in ids)
            {
                bll.Delete(id);
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除配送方式成功"); //记录日志
            return Json(new { status = 1, msg = "删除数据成功！" });
        }

        #region 赋值操作
        public Model.express OrderExpressInfo(int _id)
        {
            BLL.express bll = new BLL.express();
            Model.express model = bll.Get(_id);
            model.remark = Utils.ToTxt(model.remark);
            return model;
        }
        #endregion

        //保存
        public SaveModel OrderExpressSave(string _action, int _id, Model.express t)
        {
            BLL.express bll = new BLL.express();
            t.express_fee = Utils.StrToDecimal(t.express_fee.ToString(), 0);
            t.remark = Utils.ToHtml(t.remark);
            t.sort_id = Utils.StrToInt(t.sort_id.ToString(), 99);
            t.is_lock = DTRequest.GetFormString("is_lock").Contains("true") ? 0 : 1;

            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("order_express", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.express model = bll.Get(_id);

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改配送方式:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改物流配送成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("order_express", DTEnums.ActionEnum.Add.ToString()); //检查权限

                if (bll.Save(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加配送方式:" + t.title); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加物流配送成功！",
                    status = 1
                };
            }
        }

        public List<SelectListItem> OrderExpressTreeBind()
        {
            BLL.express bll2 = new BLL.express();
            List<Model.express> express_list = bll2.GetModelList(0, "", "title,id", "");
            List<SelectListItem> expressListItems = new List<SelectListItem>();
            foreach (var dr in express_list)
            {
                expressListItems.Add(new SelectListItem() { Text = dr.title, Value = dr.id.ToString() });
            }
            return expressListItems;
        }
        #endregion
        #endregion

        #region 会员组价格
        public List<Model.user_groups> DialogGroupPriceBind(string _strWhere, string _orderby)
        {
            BLL.user_groups bll = new BLL.user_groups();
            List<Model.user_groups> role_list = bll.GetModelList(0, _strWhere, "", _orderby);
            return role_list;
        }
        #endregion

        #region 群发
        #region 群发邮件
        #region 返回会员组所有邮箱地址
        private List<string> GetGroupEmail(ArrayList al)
        {
            List<string> list = new List<string>();
            foreach (Object obj in al)
            {
                List<Model.users> user_list = new BLL.users().GetModelList(0, "group_id=" + Convert.ToInt32(obj), "", "reg_time desc,id desc");
                foreach (var dr in user_list)
                {
                    string _email = dr.email;
                    if (!string.IsNullOrEmpty(_email))
                    {
                        list.Add(_email);
                    }
                }
            }
            return list;
        }
        #endregion
        //提交发送
        public SaveModel EmailSave()
        {
            string emailList = DTRequest.GetFormString("txtEmailList");
            string emailTitle = DTRequest.GetFormString("txtTitle");
            string emailBody = DTRequest.GetFormString("txtContent");
            string rblemailType = DTRequest.GetFormString("rblemailType");
            BLL.user_groups bll = new BLL.user_groups();
            List<Model.user_groups> groups_list = bll.GetModelList(0, "is_lock=0", "title,id", "grade asc,id asc");
            if (emailTitle.Length == 0)
            {
                return new SaveModel
                {
                    msg = "请输入邮件标题！",
                    status = 0
                };
            }
            if (emailBody.Length == 0)
            {
                return new SaveModel
                {
                    msg = "请输入邮件内容！",
                    status = 0
                };
            }
            //邮箱地址
            List<string> list = null;
            //检查发送类型
            if (rblemailType == "1")
            {
                list = new List<string>();
                if (emailList.Length == 0)
                {
                    return new SaveModel
                    {
                        msg = "请输入邮箱地址！",
                        status = 0
                    };
                }
                string[] emailArr = emailList.Split(',');
                foreach (string _email in emailArr)
                {
                    list.Add(_email);
                }
            }
            else
            {
                ArrayList al = new ArrayList();
                foreach (var item in groups_list)
                {
                    string v = DTRequest.GetFormString("cblGroupId_" + item.id);
                    if (!string.IsNullOrEmpty(v))
                    {
                        al.Add(item.id.ToString());
                    }
                }
                if (al.Count < 1)
                {
                    return new SaveModel
                    {
                        msg = "请选择会员组别！",
                        status = 0
                    };
                }
                list = GetGroupEmail(al);
            }

            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            foreach (string _email in list)
            {
                if (Utils.IsValidEmail(_email))
                {
                    try
                    {
                        DTMail.sendMail(siteConfig.emailport, siteConfig.emailsmtp, siteConfig.emailssl,
                            siteConfig.emailusername,
                            DESEncrypt.Decrypt(siteConfig.emailpassword, siteConfig.sysencryptstring),
                            siteConfig.emailnickname,
                            siteConfig.emailfrom,
                            _email,
                            emailTitle,
                            emailBody);
                        sucCount++;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog("邮箱发送错误：" + ex);
                        errorCount++;
                    }
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "成功发送邮件" + sucCount + "条，失败" + errorCount + "条！"); //记录日志
            return new SaveModel
            {
                msg = "成功发送邮件" + sucCount + "条，失败" + errorCount + "条！",
                status = 1
            };
        }
        #endregion
        #region 群发短信
        #region 返回会员组所有手机号码======
        private string GetGroupMobile(ArrayList al)
        {
            StringBuilder str = new StringBuilder();
            foreach (Object obj in al)
            {
                List<Model.users> user_list = new BLL.users().GetModelList(0, "group_id=" + Convert.ToInt32(obj), "", "reg_time desc,id desc");
                foreach (var dr in user_list)
                {
                    if (!string.IsNullOrEmpty(dr.mobile))
                    {
                        str.Append(dr.mobile + ",");
                    }
                }
            }
            return Utils.DelLastComma(str.ToString());
        }
        #endregion
        //提交发送
        public SaveModel SmsSave()
        {
            string txtMobileNumbers = DTRequest.GetFormString("txtMobileNumbers");
            string txtSmsContent = DTRequest.GetFormString("txtSmsContent");
            string rblSmsType = DTRequest.GetFormString("rblSmsType");
            string templateId = DTRequest.GetFormString("templateId");
            BLL.user_groups bll = new BLL.user_groups();
            List<Model.user_groups> groups_list = bll.GetModelList(0, "is_lock=0", "title,id", "grade asc,id asc");

            //检查短信内容
            if (txtSmsContent == "")
            {
                return new SaveModel
                {
                    msg = "请输入短信内容！",
                    status = 0
                };
            }
            //检查发送类型
            if (rblSmsType == "1")
            {
                if (txtMobileNumbers == "")
                {
                    return new SaveModel
                    {
                        msg = "请输入手机号码！",
                        status = 0
                    };
                }
                //开始发送短信
                string msg = string.Empty;
                bool results = SmsFactory.Sms().Send(txtMobileNumbers, templateId, 2, txtSmsContent, out msg);
                //bool results = new BLL.sms_message().Send(txtMobileNumbers, txtSmsContent, 2, out msg);
                if (results)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "发送手机短信"); //记录日志
                    return new SaveModel
                    {
                        msg = msg,
                        status = 1
                    };
                }
                return new SaveModel
                {
                    msg = msg,
                    status = 1
                };
            }
            else
            {
                ArrayList al = new ArrayList();
                foreach (var item in groups_list)
                {
                    string v = DTRequest.GetFormString("cblGroupId_" + item.id);
                    if (!string.IsNullOrEmpty(v))
                    {
                        al.Add(item.id.ToString());
                    }
                }
                if (al.Count < 1)
                {
                    return new SaveModel
                    {
                        msg = "请选择会员组别！",
                        status = 0
                    };
                }
                string _mobiles = GetGroupMobile(al);
                //开始发送短信
                string msg = string.Empty;
                bool results = new BLL.sms_message().Send(_mobiles, txtSmsContent, 2, out msg);
                if (results)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "发送手机短信"); //记录日志
                    return new SaveModel
                    {
                        msg = msg,
                        status = 1
                    };
                }
                return new SaveModel
                {
                    msg = msg,
                    status = 1
                };
            }
        }
        #endregion
        #endregion

        #region 微信
        #region 绑定公众账户
        public List<Model.weixin_account> WeiXinBind()
        {
            List<Model.weixin_account> wxlist = new BLL.weixin_account().GetModelList(0, "is_push=1", "", "sort_id asc,id desc");
            return wxlist;
        }

        public List<SelectListItem> WeixinTreeBind(string strWhere, string strOrder)
        {
            BLL.weixin_account bll = new BLL.weixin_account();
            List<Model.weixin_account> account_list = bll.GetModelList(0, strWhere, "name,id", strOrder);
            List<SelectListItem> weixinListItems = new List<SelectListItem>();
            foreach (Model.weixin_account dr in account_list)
            {
                weixinListItems.Add(new SelectListItem() { Text = dr.name, Value = dr.id.ToString() });
            }
            return weixinListItems;
        }
        #endregion
        #region 回复消息
        public SaveModel WeiXinSubscribeSave(string _action, int _id, string txtContent)
        {
            //检查权限
            switch (_action.ToLower())
            {
                case "default":
                    ChkAdminLevel("weixin_subscribe_default", DTEnums.ActionEnum.Edit.ToString());
                    break;
                case "cancel":
                    ChkAdminLevel("weixin_subscribe_cancel", DTEnums.ActionEnum.Edit.ToString());
                    break;
                default:
                    ChkAdminLevel("weixin_subscribe_subscribe", DTEnums.ActionEnum.Edit.ToString());
                    break;
            }
            //开始保存数据
            string ruleName = string.Empty; //规格名称
            int ruleId = DTRequest.GetFormInt("hideId", 0); //规则ID
            int requestType = DTRequest.GetFormInt("hideRequestType", 0); //请求的类别
            int responseType = DTRequest.GetFormInt("rblResponseType", 0);  //回复的类别
            if (requestType == 6)
            {
                ruleName = "关注时的触发内容";
            }
            else if (requestType == 0)
            {
                ruleName = "默认回复内容";
            }
            else if (requestType == 7)
            {
                ruleName = "取消关注时的触发内容";
            }
            Model.weixin_request_rule model = new BLL.weixin_request_rule().GetModel(ruleId);
            if (model == null)
            {
                model = new Model.weixin_request_rule();
            }
            model.account_id = _id;
            model.name = ruleName;
            model.request_type = requestType;
            model.is_default = 0;
            model.add_time = DateTime.Now;

            if (responseType == 0) //纯文本
            {
                if (txtContent.Length == 0)
                {
                    return new SaveModel { msg = "回复内容不能为空！", status = 0 };
                }
                model.response_type = 1;//回复的类型:文本1，图文2，语音3，视频4,第三方接口5
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                ls.Add(new Model.weixin_request_content() { account_id = _id, rule_id = ruleId, content = txtContent });
                model.contents = ls;
            }
            else if (DTRequest.GetFormInt("rblResponseType", 0) == 1) //图文
            {
                model.response_type = 2;//回复的类型:文本1，图文2，语音3，视频4,第三方接口5

                #region 赋值规则图片
                string[] itemIdArr = DTRequest.GetFormValues("item_id");
                string[] itemTitleArr = DTRequest.GetFormValues("item_title");
                string[] itemContentArr = DTRequest.GetFormValues("item_content");
                string[] itemImgUrlArr = DTRequest.GetFormValues("item_imgurl");
                string[] itemLinkUrlArr = DTRequest.GetFormValues("item_linkurl");
                string[] itemSortIdArr = DTRequest.GetFormValues("item_sortid");
                if (itemIdArr != null && itemTitleArr != null && itemImgUrlArr != null && itemLinkUrlArr != null && itemSortIdArr != null && itemContentArr != null)
                {
                    if ((itemIdArr.Length == itemTitleArr.Length) && (itemTitleArr.Length == itemImgUrlArr.Length) && (itemImgUrlArr.Length == itemLinkUrlArr.Length)
                        && (itemLinkUrlArr.Length == itemSortIdArr.Length) && (itemSortIdArr.Length == itemContentArr.Length))
                    {
                        List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                        for (int i = 0; i < itemIdArr.Length; i++)
                        {
                            Model.weixin_request_content modelt = new Model.weixin_request_content();
                            modelt.id = Utils.StrToInt(itemIdArr[i], 0);
                            modelt.account_id = _id;
                            modelt.rule_id = ruleId;
                            modelt.title = itemTitleArr[i];
                            modelt.content = itemContentArr[i];
                            modelt.img_url = itemImgUrlArr[i];
                            modelt.link_url = itemLinkUrlArr[i];
                            modelt.sort_id = Utils.StrToInt(itemSortIdArr[i], 99);
                            ls.Add(modelt);
                        }
                        model.contents = ls;
                    }
                }
                else
                {
                    model.contents = null;
                }
                #endregion
            }
            else if (DTRequest.GetFormInt("rblResponseType", 0) == 2) //语音
            {
                if (DTRequest.GetFormString("txtSoundTitle").Length == 0)
                {
                    return new SaveModel { msg = "语音标题不能为空！", status = 0 };
                }
                if (DTRequest.GetFormString("txtSoundUrl").Length == 0)
                {
                    return new SaveModel { msg = "文件地址不能为空！", status = 0 };
                }
                model.response_type = 3;//回复的类型:文本1，图文2，语音3，视频4,第三方接口5
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                ls.Add(new Model.weixin_request_content()
                {
                    account_id = _id,
                    rule_id = ruleId,
                    title = DTRequest.GetFormString("txtSoundTitle"),
                    media_url = DTRequest.GetFormString("txtSoundUrl"),
                    content = DTRequest.GetFormString("txtSoundContent")
                });
                model.contents = ls;
            }
            //判断是新增还是修改
            if (model.id > 0 && new BLL.weixin_request_rule().Update(model))
            {
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "新增微信" + ruleName); //记录日志
                return new SaveModel { msg = "编辑" + ruleName + "成功！", status = 1 };
            }
            else if (new BLL.weixin_request_rule().Add(model) > 0)
            {
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "编辑微信" + ruleName); //记录日志
                return new SaveModel { msg = "新增" + ruleName + "成功！", status = 1 };
            }
            return new SaveModel { msg = "保存" + ruleName + "失败！", status = 0 };
        }
        #endregion
        #region 自定义菜单管理
        public JsonResult WeixinMenuDelete(List<int> ids)
        {
            BLL.weixin_account bll = new BLL.weixin_account();
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            foreach (int id in ids)
            {
                Model.weixin_account model = new BLL.weixin_account().GetModel(id);
                if (model != null)
                {
                    string error = string.Empty; //定义错误
                    string token = cpp.GetAccessToken(id, out error); //获取最新的AccessToken
                    if (string.IsNullOrEmpty(error))
                    {
                        var result = Senparc.Weixin.MP.CommonAPIs.CommonApi.DeleteMenu(token);
                        if ((int)result.errcode == 0)
                        {
                            sucCount += 1;
                        }
                        else
                        {
                            errorCount += 1;
                        }
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "清空公众平台自定义菜单成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 数据绑定
        public Page<Model.weixin_account> WeixinMenuBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.weixin_account bll = new BLL.weixin_account();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        public SaveModel WeixinMenuSave(int _id)
        {
            try
            {
                string error = string.Empty;
                string accessToken = cpp.GetAccessToken(_id, out error);

                if (!string.IsNullOrEmpty(error))
                {
                    return new SaveModel
                    {
                        msg = error,
                        status = 0
                    };
                }

                //重新整理按钮信息
                ButtonGroup bg = new ButtonGroup();
                string txtName = string.Empty;
                string txtKey = string.Empty;
                string txtUrl = string.Empty;
                IList<BaseButton> topList = new List<BaseButton>();
                IList<SingleButton> subList = new List<SingleButton>();
                //菜单设置
                for (int i = 0; i < 3; i++)
                {
                    txtName = DTRequest.GetFormString("txtTop" + (i + 1) + "Name");
                    txtKey = DTRequest.GetFormString("txtTop" + (i + 1) + "Key");
                    txtUrl = DTRequest.GetFormString("txtTop" + (i + 1) + "Url");
                    if (txtName == "")
                    {
                        // 如果名称为空，则忽略该菜单，以及下面的子菜单
                        continue;
                    }

                    subList = new List<SingleButton>();
                    string txtSubName = string.Empty;
                    string txtSubKey = string.Empty;
                    string txtSubUrl = string.Empty;
                    for (int j = 0; j < 5; j++)
                    {
                        //子菜单的设置
                        txtSubName = DTRequest.GetFormString("txtMenu" + (i + 1) + (j + 1) + "Name");
                        txtSubKey = DTRequest.GetFormString("txtMenu" + (i + 1) + (j + 1) + "Key");
                        txtSubUrl = DTRequest.GetFormString("txtMenu" + (i + 1) + (j + 1) + "Url");
                        if (txtSubName == "")
                        {
                            continue;
                        }

                        if (txtSubUrl != "")
                        {
                            SingleViewButton sub = new SingleViewButton();
                            sub.name = txtSubName;
                            sub.url = txtSubUrl;
                            subList.Add(sub);
                        }
                        else if (txtSubKey != "")
                        {
                            SingleClickButton sub = new SingleClickButton();
                            sub.name = txtSubName;
                            sub.key = txtSubKey;
                            subList.Add(sub);
                        }
                        else
                        {
                            //报错 :子菜单必须有key和name
                            return new SaveModel
                            {
                                msg = "二级菜单的名称和key或者url必填！",
                                status = 0
                            };
                        }
                    }

                    if (subList != null && subList.Count > 0)
                    {
                        //有子菜单, 该一级菜单是SubButton
                        if (subList.Count < 1)
                        {
                            return new SaveModel
                            {
                                msg = "子菜单个数必须为2至5个！",
                                status = 0
                            };
                        }
                        SubButton topButton = new SubButton(Utils.CutString(txtName, 16));
                        topButton.sub_button.AddRange(subList);
                        topList.Add(topButton);
                    }
                    else
                    {
                        // 无子菜单
                        if (txtKey == "" && txtUrl == "")
                        {
                            return new SaveModel
                            {
                                msg = "如无子菜单，必须填写Key或者URL值！",
                                status = 0
                            };
                        }

                        if (txtUrl != "")
                        {  //view 页面跳转
                            SingleViewButton topSingleButton = new SingleViewButton();
                            topSingleButton.name = txtName;
                            topSingleButton.url = txtUrl;
                            topList.Add(topSingleButton);
                        }
                        else if (txtKey != "")
                        {
                            SingleClickButton topSingleButton = new SingleClickButton();
                            topSingleButton.name = txtName;
                            topSingleButton.key = txtKey;
                            topList.Add(topSingleButton);
                        }
                    }
                }

                bg.button.AddRange(topList);
                Senparc.Weixin.Entities.WxJsonResult jsonResult = Senparc.Weixin.MP.CommonAPIs.CommonApi.CreateMenu(accessToken, bg);
                return new SaveModel
                {
                    msg = "自定义菜单保存成功！",
                    status = 1
                };
            }
            catch (Exception ex)
            {
                return new SaveModel
                {
                    msg = "出错了：" + ex.Message,
                    status = 0
                };
            }
        }
        #endregion
        #region 文本回复管理
        //批量删除

        public JsonResult WeixinTextDelete(List<int> ids)
        {
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除微信文本回复成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 数据绑定
        public Page<Model.weixin_request_rule> WeixinTextBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        #region 赋值操作
        public Model.weixin_request_rule WeixinTextInfo(int _id)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            Model.weixin_request_rule model = bll.GetModel(_id);
            return model;
        }
        #endregion

        public SaveModel WeixinTextSave(string _action, int _id, Model.weixin_request_rule t)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            string txtContent = DTRequest.GetFormString("txtContent");
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("weixin_response_text", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.weixin_request_rule model = bll.GetModel(_id);
                t.request_type = model.request_type;
                t.response_type = model.response_type;
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                ls.Add(new Model.weixin_request_content() { account_id = t.account_id, rule_id = model.id, content = txtContent });
                t.contents = ls;

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改微信文本回复，关健字:" + model.keywords); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改文本回复成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("weixin_response_text", DTEnums.ActionEnum.Add.ToString()); //检查权限
                t.name = "文本回复";
                t.request_type = 1;
                t.response_type = 1;
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                ls.Add(new Model.weixin_request_content() { account_id = t.account_id, content = txtContent });
                t.contents = ls;
                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加微信文本回复，关健字:" + t.keywords); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加文本回复成功！",
                    status = 1
                };
            }
        }
        #endregion
        #region 回复消息
        #region 赋值操作
        public Model.weixin_request_rule SubscribeInfo(int account_id)
        {
            string requestType = DTRequest.GetQueryString("hideRequestType");
            Model.weixin_request_rule ruleModel = new BLL.weixin_request_rule().GetModel(account_id, Utils.StrToInt(requestType, 0)); //获取规则
            return ruleModel;
        }
        #endregion
        public JsonResult SubscribeSave(string action, int id, string txtContent)
        {
            //检查权限
            switch (action.ToLower())
            {
                case "default":
                    ChkAdminLevel("weixin_subscribe_default", DTEnums.ActionEnum.Edit.ToString());
                    break;
                case "cancel":
                    ChkAdminLevel("weixin_subscribe_cancel", DTEnums.ActionEnum.Edit.ToString());
                    break;
                default:
                    ChkAdminLevel("weixin_subscribe_subscribe", DTEnums.ActionEnum.Edit.ToString());
                    break;
            }
            //开始保存数据
            string ruleName = string.Empty; //规格名称
            int ruleId = DTRequest.GetFormInt("hideId"); //规则ID
            int requestType = DTRequest.GetFormInt("hideRequestType");//请求的类别
            int responseType = DTRequest.GetFormInt("rblResponseType"); //回复的类别
            if (requestType == 6)
            {
                ruleName = "关注时的触发内容";
            }
            else if (requestType == 0)
            {
                ruleName = "默认回复内容";
            }
            else if (requestType == 7)
            {
                ruleName = "取消关注时的触发内容";
            }
            Model.weixin_request_rule model = new BLL.weixin_request_rule().GetModel(ruleId);
            if (model == null)
            {
                model = new Model.weixin_request_rule();
            }
            model.account_id = id;
            model.name = ruleName;
            model.request_type = requestType;
            model.is_default = 0;
            model.add_time = DateTime.Now;

            if (responseType == 0) //纯文本
            {
                if (txtContent.Length == 0)
                {
                    return Json(new { status = 0, msg = "回复内容不能为空！" });
                }
                model.response_type = 1;//回复的类型:文本1，图文2，语音3，视频4,第三方接口5
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                ls.Add(new Model.weixin_request_content() { account_id = id, rule_id = ruleId, content = txtContent });
                model.contents = ls;
            }
            else if (DTRequest.GetFormInt("rblResponseType") == 1) //图文
            {
                model.response_type = 2;//回复的类型:文本1，图文2，语音3，视频4,第三方接口5

                #region 赋值规则图片
                string[] itemIdArr = DTRequest.GetFormValues("item_id");
                string[] itemTitleArr = DTRequest.GetFormValues("item_title");
                string[] itemContentArr = DTRequest.GetFormValues("item_content");
                string[] itemImgUrlArr = DTRequest.GetFormValues("item_imgurl");
                string[] itemLinkUrlArr = DTRequest.GetFormValues("item_linkurl");
                string[] itemSortIdArr = DTRequest.GetFormValues("item_sortid");
                if (itemIdArr != null && itemTitleArr != null && itemImgUrlArr != null && itemLinkUrlArr != null && itemSortIdArr != null && itemContentArr != null)
                {
                    if ((itemIdArr.Length == itemTitleArr.Length) && (itemTitleArr.Length == itemImgUrlArr.Length) && (itemImgUrlArr.Length == itemLinkUrlArr.Length)
                        && (itemLinkUrlArr.Length == itemSortIdArr.Length) && (itemSortIdArr.Length == itemContentArr.Length))
                    {
                        List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                        for (int i = 0; i < itemIdArr.Length; i++)
                        {
                            Model.weixin_request_content modelt = new Model.weixin_request_content();
                            modelt.id = Utils.StrToInt(itemIdArr[i], 0);
                            modelt.account_id = id;
                            modelt.rule_id = ruleId;
                            modelt.title = itemTitleArr[i];
                            modelt.content = itemContentArr[i];
                            modelt.img_url = itemImgUrlArr[i];
                            modelt.link_url = itemLinkUrlArr[i];
                            modelt.sort_id = Utils.StrToInt(itemSortIdArr[i], 99);
                            ls.Add(modelt);
                        }
                        model.contents = ls;
                    }
                }
                else
                {
                    model.contents = null;
                }
                #endregion
            }
            else if (DTRequest.GetFormString("rblResponseType") == "2") //语音
            {
                if (DTRequest.GetFormString("txtSoundTitle").Length == 0)
                {
                    return Json(new { status = 0, msg = "语音标题不能为空！" });
                }
                if (DTRequest.GetFormString("txtSoundUrl").Length == 0)
                {
                    return Json(new { status = 0, msg = "文件地址不能为空！" });
                }
                model.response_type = 3;//回复的类型:文本1，图文2，语音3，视频4,第三方接口5
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                ls.Add(new Model.weixin_request_content()
                {
                    account_id = id,
                    rule_id = ruleId,
                    title = DTRequest.GetFormString("txtSoundTitle"),
                    media_url = DTRequest.GetFormString("txtSoundUrl"),
                    content = DTRequest.GetFormString("txtSoundContent")
                });
                model.contents = ls;
            }
            //判断是新增还是修改
            if (model.id > 0 && new BLL.weixin_request_rule().Update(model))
            {
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "新增微信" + ruleName); //记录日志
                return Json(new { status = 1, msg = "编辑" + ruleName + "成功！", url = "../subscribe_list/index?action=" + action + "&id=" + id });
            }
            else if (new BLL.weixin_request_rule().Add(model) > 0)
            {
                AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "编辑微信" + ruleName); //记录日志
                return Json(new { status = 1, msg = "新增" + ruleName + "成功！", url = "../subscribe_list/index?action=" + action + "&id=" + id });
            }
            return Json(new { status = 0, msg = "保存" + ruleName + "失败！" });
        }
        #region 删除

        public SaveModel SubscribeDel(string action, int accountId, int hideReqestType)
        {
            //检查权限
            switch (action.ToLower())
            {
                case "default":
                    ChkAdminLevel("weixin_subscribe_default", DTEnums.ActionEnum.Delete.ToString());
                    break;
                case "cancel":
                    ChkAdminLevel("weixin_subscribe_cancel", DTEnums.ActionEnum.Delete.ToString());
                    break;
                default:
                    ChkAdminLevel("weixin_subscribe_subscribe", DTEnums.ActionEnum.Delete.ToString());
                    break;
            }
            //删除操作
            Model.weixin_request_rule ruleModel = new BLL.weixin_request_rule().GetModel(accountId, hideReqestType); //获取规则
            if (ruleModel != null)
            {
                bool result = new BLL.weixin_request_rule().Delete(ruleModel.id);
                if (result)
                {
                    AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除" + ruleModel.name + "，公众账户ID：" + accountId); //记录日志
                    return new SaveModel { msg = "删除消息成功！", status = 1 };
                }
                return new SaveModel { msg = "删除消息失败！", status = 0 };
            }
            return new SaveModel { msg = "未找到对象！", status = 0 };
        }
        #endregion
        #endregion
        #region 语音回复管理
        //批量删除

        public JsonResult WeiXinSoundDelete(List<int> ids)
        {
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除微信语音回复成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 数据绑定
        public Page<Model.weixin_request_rule> WeiXinSoundBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        #region 赋值操作
        public Model.weixin_request_rule WeiXinSoundInfo(int _id)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            Model.weixin_request_rule model = bll.GetModel(_id);
            return model;
        }
        #endregion

        public SaveModel WeiXinSoundSave(string _action, int _id, Model.weixin_request_rule t)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            string errmsg = string.Empty;
            string txtContent = DTRequest.GetFormString("txtContent");
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("weixin_response_sound", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.weixin_request_rule model = bll.GetModel(_id);
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                ls.Add(new Model.weixin_request_content() { account_id = t.account_id, rule_id = model.id, content = txtContent });
                t.contents = ls;

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改微信语音回复，关健字:" + model.keywords); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "修改语音回复成功！",
                    status = 1
                };
            }
            else //添加
            {
                ChkAdminLevel("weixin_response_sound", DTEnums.ActionEnum.Add.ToString()); //检查权限
                t.name = "语音回复";
                t.request_type = 1;
                t.response_type = 3;
                List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                //上传素材到微信服务器
                string mediaId = new API.Weixin.Common.CRMComm().UploadForeverMedia(t.account_id, Utils.GetMapPath(DTRequest.GetFormString("txtImgUrl")), out errmsg);
                ls.Add(new Model.weixin_request_content()
                {
                    account_id = t.account_id,
                    title = DTRequest.GetFormString("txtTitle"),
                    img_url = DTRequest.GetFormString("txtImgUrl"),
                    media_id = mediaId,
                    media_url = DTRequest.GetFormString("txtMediaUrl"),
                    meida_hd_url = DTRequest.GetFormString("txtMediaUrl"),
                    content = txtContent
                });
                t.contents = ls;
                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加微信语音回复，关健字:" + t.keywords); //记录日志
                }
                else
                {
                    return new SaveModel
                    {
                        msg = "保存过程中发生错误！",
                        status = 0
                    };
                }
                return new SaveModel
                {
                    msg = "添加语音回复成功！",
                    status = 1
                };
            }
        }
        #endregion
        #region 请求回复记录
        //批量删除

        public JsonResult WeiXinResponseDelete(List<int> ids)
        {
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.weixin_response_content bll = new BLL.weixin_response_content();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除微信请求回复" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 数据绑定
        public Page<Model.weixin_response_content> WeiXinResponseBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.weixin_response_content bll = new BLL.weixin_response_content();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion
        #endregion
        #region 图文回复管理
        //批量删除

        public JsonResult WeiXinPictureDelete(List<int> ids)
        {
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除微信图文回复成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 数据绑定
        public Page<Model.weixin_request_rule> WeiXinPictureBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        #region 赋值操作
        public Model.weixin_request_rule WeiXinPictureInfo(int _id)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            Model.weixin_request_rule model = bll.GetModel(_id);
            return model;
        }
        #endregion

        public SaveModel WeiXinPictureSave(string _action, int _id, Model.weixin_request_rule t)
        {
            BLL.weixin_request_rule bll = new BLL.weixin_request_rule();
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("weixin_response_picture", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                Model.weixin_request_rule model = bll.GetModel(_id);
                #region 赋值规则图片
                string[] itemIdArr = DTRequest.GetFormValues("item_id");
                string[] itemTitleArr = DTRequest.GetFormValues("item_title");
                string[] itemContentArr = DTRequest.GetFormValues("item_content");
                string[] itemImgUrlArr = DTRequest.GetFormValues("item_imgurl");
                string[] itemLinkUrlArr = DTRequest.GetFormValues("item_linkurl");
                string[] itemSortIdArr = DTRequest.GetFormValues("item_sortid");
                if (itemIdArr != null && itemTitleArr != null && itemImgUrlArr != null && itemLinkUrlArr != null && itemSortIdArr != null && itemContentArr != null)
                {
                    if ((itemIdArr.Length == itemTitleArr.Length) && (itemTitleArr.Length == itemImgUrlArr.Length) && (itemImgUrlArr.Length == itemLinkUrlArr.Length)
                        && (itemLinkUrlArr.Length == itemSortIdArr.Length) && (itemSortIdArr.Length == itemContentArr.Length))
                    {
                        List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                        for (int i = 0; i < itemIdArr.Length; i++)
                        {
                            Model.weixin_request_content modelt = new Model.weixin_request_content();
                            modelt.id = Utils.StrToInt(itemIdArr[i], 0);
                            modelt.rule_id = model.id;
                            modelt.account_id = t.account_id;
                            modelt.title = itemTitleArr[i];
                            modelt.content = itemContentArr[i];
                            modelt.img_url = itemImgUrlArr[i];
                            modelt.link_url = itemLinkUrlArr[i];
                            modelt.sort_id = Utils.StrToInt(itemSortIdArr[i], 99);
                            ls.Add(modelt);
                        }
                        t.contents = ls;
                    }
                }
                else
                {
                    t.contents = null;
                }
                #endregion

                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改微信图文回复，关健字:" + model.keywords); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "修改图文回复成功！", status = 1 };
            }
            else //添加
            {
                ChkAdminLevel("weixin_response_picture", DTEnums.ActionEnum.Add.ToString()); //检查权限
                t.name = "图文回复";
                t.request_type = 1; //关键词回复
                t.response_type = 2; //回复的类型:文本1，图文2，图文3，视频4,第三方接口5
                #region 赋值规则图片
                string[] itemIdArr = DTRequest.GetFormValues("item_id");
                string[] itemTitleArr = DTRequest.GetFormValues("item_title");
                string[] itemContentArr = DTRequest.GetFormValues("item_content");
                string[] itemImgUrlArr = DTRequest.GetFormValues("item_imgurl");
                string[] itemLinkUrlArr = DTRequest.GetFormValues("item_linkurl");
                string[] itemSortIdArr = DTRequest.GetFormValues("item_sortid");
                if (itemIdArr != null && itemTitleArr != null && itemImgUrlArr != null && itemLinkUrlArr != null && itemSortIdArr != null && itemContentArr != null)
                {
                    if ((itemIdArr.Length == itemTitleArr.Length) && (itemTitleArr.Length == itemImgUrlArr.Length) && (itemImgUrlArr.Length == itemLinkUrlArr.Length)
                        && (itemLinkUrlArr.Length == itemSortIdArr.Length) && (itemSortIdArr.Length == itemContentArr.Length))
                    {
                        List<Model.weixin_request_content> ls = new List<Model.weixin_request_content>();
                        for (int i = 0; i < itemIdArr.Length; i++)
                        {
                            Model.weixin_request_content modelt = new Model.weixin_request_content();
                            modelt.id = Utils.StrToInt(itemIdArr[i], 0);
                            modelt.account_id = t.account_id;
                            modelt.title = itemTitleArr[i];
                            modelt.content = itemContentArr[i];
                            modelt.img_url = itemImgUrlArr[i];
                            modelt.link_url = itemLinkUrlArr[i];
                            modelt.sort_id = Utils.StrToInt(itemSortIdArr[i], 99);
                            ls.Add(modelt);
                        }
                        t.contents = ls;
                    }
                }
                else
                {
                    t.contents = null;
                }
                #endregion
                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加微信图文回复，关健字:" + t.keywords); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "添加图文回复成功！", status = 1 };
            }
        }
        #endregion
        #region 公众账户管理
        //批量删除

        public JsonResult WeixinAccountDelete(List<int> ids)
        {
            int sucCount = 0; //成功数量
            int errorCount = 0; //失败数量
            BLL.weixin_account bll = new BLL.weixin_account();
            foreach (int id in ids)
            {
                if (bll.Delete(id))
                {
                    sucCount++;
                }
                else
                {
                    errorCount++;
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除微信公众平台成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            return Json(new { status = 1, msg = "删除成功" + sucCount + "条，失败" + errorCount + "条！" });
        }

        #region 数据绑定
        public Page<Model.weixin_account> WeixinAccountBind(string _strWhere, string _orderby, int page = 1, int pageSize = 10)
        {
            BLL.weixin_account bll = new BLL.weixin_account();
            var resultlist = bll.GetQueryPage(page, pageSize, _strWhere, _orderby);
            return resultlist;
        }
        #endregion

        #region 赋值操作
        public Model.weixin_account WeixinAccountInfo(int _id)
        {
            BLL.weixin_account bll = new BLL.weixin_account();
            Model.weixin_account model = bll.Get(_id);
            return model;
        }
        #endregion

        public SaveModel WeixinAccountSave(string _action, int _id, Model.weixin_account t)
        {
            BLL.weixin_account bll = new BLL.weixin_account();
            t.is_push = DTRequest.GetFormString("is_push").Contains("true") ? 1 : 0;
            if (_action == DTEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("weixin_account_manage", DTEnums.ActionEnum.Edit.ToString()); //检查权限
                if (bll.Update(t))
                {
                    AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改公众账户:" + t.name); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "修改公众账户成功！", status = 1 };
            }
            else //添加
            {
                ChkAdminLevel("weixin_account_manage", DTEnums.ActionEnum.Add.ToString()); //检查权限
                if (bll.Add(t) > 0)
                {
                    AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "增加公众账户:" + t.name); //记录日志
                }
                else
                {
                    return new SaveModel { msg = "保存过程中发生错误！", status = 0 };
                }
                return new SaveModel { msg = "添加公众账户成功！", status = 1 };
            }
        }
        #endregion
        #endregion

        #region 统一方法
        #region 判断频道是否存在
        public bool IsChannel(int channel_id)
        {
            bool IsBool = false;
            Model.site_channel model = new BLL.site_channel().GetModel(channel_id);
            if (model != null)
            {
                IsBool = true;
            }
            return IsBool;
        }
        public bool IsChannel(string channel_name)
        {
            bool IsBool = false;
            Model.site_channel model = new BLL.site_channel().GetModel(channel_name);
            if (model != null)
            {
                IsBool = true;
            }
            return IsBool;
        }
        #endregion
        #region 返回站点链接网址=====
        public string GetLinkDomain(int channel_id)
        {
            Model.site_channel channelModel = new BLL.site_channel().GetModel(channel_id);
            Model.sites siteModel = new BLL.sites().GetModel(channelModel.site_id);
            if (siteModel == null || string.IsNullOrEmpty(siteModel.domain))
            {
                return siteConfig.weburl;
            }
            return siteModel.domain;
        }
        #endregion
        #region 替换内容图片路径=====
        private string ReplaceImagesPath(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
            MatchCollection m = reg.Matches(content);
            foreach (Match math in m)
            {
                string imgUri = math.Groups[1].Value;
                //如果是本地图片，则加上http://网址/网站安装目录/上传目录/文件名
                if (imgUri.StartsWith(siteConfig.webpath + siteConfig.filepath + "/"))
                {
                    string newImgPath = "http://" + System.Web.HttpContext.Current.Request.Url.Authority.ToLower() + imgUri;
                    content = content.Replace(imgUri, newImgPath);
                }
            }
            return content;
        }
        #endregion
        #region 获取编辑器内容第一张图片
        public string AutoGetFirstImage(string content, Model.site_channel channelModel)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
            Match m = reg.Match(content);
            if (m.Success)
            {
                string imgUri = m.Groups[1].Value;
                //数据
                byte[] byteData = null;
                //判断是否是云存储
                if (imgUri.StartsWith("http") || imgUri.StartsWith("https://"))
                {
                    WebClient client = new WebClient();
                    byteData = client.DownloadData(imgUri);
                    client.Dispose();
                }
                else
                {
                    string fullName = Utils.GetMapPath(imgUri);
                    if (System.IO.File.Exists(fullName))
                    {
                        FileStream fs = System.IO.File.OpenRead(fullName);
                        BinaryReader br = new BinaryReader(fs);
                        br.BaseStream.Seek(0, SeekOrigin.Begin);
                        byteData = br.ReadBytes((int)br.BaseStream.Length);
                        fs.Close();
                    }
                }
                var ext = Path.GetExtension(imgUri); //扩展名
                var thum = channelModel.channel_thums.Find(p => p.is_lock == 0 && p.class_id == 1);
                if (thum != null)
                {
                    byteData = Thumbnail.MakeThumbnailImage(byteData, ext, thum.width, thum.height, GetTypeId(thum.typeid));
                }
                string json = JsonConvert.SerializeObject(new UpLoad().FileSaveAs("img", byteData, imgUri, false, false, true, false, 0, 0, string.Empty, false, out string fileImg).Data);
                if (json.IndexOf("成功") > 0)
                {
                    //返回
                    return JsonHelper.GetString(json, "path");
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取缩略图生成方式
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        private string GetTypeId(int typeid)
        {
            switch (typeid)
            {
                case 1:
                    return "HWB";
                case 2:
                    return "HW";
                case 3:
                    return "W";
                case 4:
                    return "H";
                default:
                    return "Cut";
            }
        }
        #endregion
        #region 根据视频地址获取图片
        //public string VideoGetFirstImage(string video, Model.site_channel channelModel)
        //{

        //}
        #endregion
        #region 获取短信数量
        public void SetSmsCount(out string smsTip, out string smsCount)
        {
            //smsTip = "暂时放弃请求！";
            //smsCount = "0";
            int total = 0;
            string errorMsg = string.Empty;
            if (!new BLL.sms_message().GetAccountQuantity(out total, out errorMsg))
            {
                smsTip = "查询失败：";
                smsCount = errorMsg;
            }
            else
            {
                int start = siteConfig.smsqueryformat.IndexOf("{");
                int len = siteConfig.smsqueryformat.Length - start;
                smsTip = siteConfig.smsqueryformat.Substring(0, start);
                smsCount = siteConfig.smsqueryformat.Substring(start, len).Replace("{0}", total.ToString());
            }
        }
        #endregion
        #endregion
    }
}